text:
Interacting with a video game - Keyboard & LUFA
I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command.
For instance, I can have a pushbutton that when pressed, it activates Keyboard.Write('J'). While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one J within that time frame and do the assigned game command.
Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send Keyboard.Write('J'), this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.
/*
  Keyboard Message test

  For the Arduino Leonardo and Micro.

  Sends a text string when a button is pressed.

  The circuit:
  - pushbutton attached from pin 4 to +5V
  - 10 kilohm resistor attached from pin 4 to ground

  created 24 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe
  modified 11 Nov 2013
  by Scott Fitzgerald

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/KeyboardMessage
*/

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.write('J');
    //Keyboard.print("You pressed the button ");
    //Keyboard.print(counter);
    //Keyboard.println(" times.");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code.
Does anyone have a clue of why this might be?

Please post your code that is doing what you don't want it to do. For your game, it's likely that either that the game only wants one J, or that it can detect when J is pushed down, and when J is released. You will have to adjust your Arduino code to do the same.

Your button is not debounced. It may be registered as pressed several times for just one physical press.

Have you tested not in the game? (e.g. in notepad) Do you intend it to send SHIFT-J (capital J) or do you want just the j key?

When I tested in Notepad, It sends one Capital J. And it does work within the game, it's just that I have to rapidly press it (for 3 seconds for example) just for it to register once within the game as a command.

It is quite common for games to be quite slow at reading the keyboard.
The Leonardo's Keyboard.write() command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.
The trick here is actually to slow down the Leonardo's sending, by not using Keyboard.write(). Instead you need to press the key, wait a moment, then release the key:
Keyboard.press('j');
delay(1);
Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.

Okay, I'll give that a try.

This definitely resolved my issue. Somewhere between 30-40 ms delay is the spot. Now I need to somehow figure if LUFA can achieve this.


text:
How can I hack my intercom system to buzz people in remotely?
How would you go about activating this button remotely?
This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

Check, how the button is connected on the board, if you can. Check, if there is any electrical load is connected to it (which would need a specific current to flow at minimum). Check, which voltage the system and especially the microcontroller use. Then maybe you can use a transistor (or relay for heavy load) to bridge the button depending on a voltage, that can be controlled by your MKR (note that it runs on 3.3V). Do your research and then edit your question to more precisely state the problem.

Agreed.  Please take the http://www.arduino.stackexchange.com/Tour to see how to format a question.  You are welcome here but we'll need more information in order to be able to help.

use a relay module; it's the safest simplest most compatible way.

3 possible solutions:

Connect the 2 contact for the button to a relay and control that relay from the arduino (example) But the kit you have doesn't include a relay.
Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.

Use an optocoupler. It isolates the Arduino, just like the relay does, but doesn’t require as much power as the relay (and doesn’t make any noise).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Using 4 identical sensors on the I2C bus
I am using 4 Pololu VL6180X ToF sensors on the Arduino UNO for a school project but just can't seem to get it working correctly. I understand that I need to hold them in reset and change the I2C address of each sensor after waking them up, but the code I have doesn't work. Is the problem some flawed understanding of the C language?
This is the .h file I wrote (distSensors.h):
/*
This module is used to interface with the distance sensors.
*/
#ifndef DISTSENSORS_FILE
#define DISTSENSORS_FILE

#include "vl6180x/VL6180X.h"
#include "globals.h"

// pins connected to VL6180 GPIO used to hold sensor in reset
#define NORTH_SHUTDOWN 13
#define EAST_SHUTDOWN 1
#define WEST_SHUTDOWN 0

// threshold distance for detectWall (mm)
double const WALL = 70;

// initializes sensor
void initSensor(VL6180X* sensor) {
  (*sensor).init();
  (*sensor).configureDefault();
  (*sensor).setTimeout(500);
}

void changeAddress(VL6180X* sensor, int address) {
  (*sensor).setAddress(address);
}

// sensors
VL6180X sensorNorth;
VL6180X sensorSouth;
VL6180X sensorWest;
VL6180X sensorEast;

void setupSensors() {
  // shutdown pins
  pinMode(NORTH_SHUTDOWN, OUTPUT);
  pinMode(WEST_SHUTDOWN, OUTPUT);
  pinMode(EAST_SHUTDOWN, OUTPUT);

  // hold each sensor in shutdown initially
  digitalWrite(NORTH_SHUTDOWN, LOW);
  digitalWrite(WEST_SHUTDOWN, LOW);
  digitalWrite(EAST_SHUTDOWN, LOW);
  delay(10);

  digitalWrite(NORTH_SHUTDOWN, HIGH);
  digitalWrite(WEST_SHUTDOWN, HIGH);
  digitalWrite(EAST_SHUTDOWN, HIGH);

  digitalWrite(NORTH_SHUTDOWN, LOW);
  digitalWrite(WEST_SHUTDOWN, LOW);
  digitalWrite(EAST_SHUTDOWN, LOW);

  // wake sensors and change address one by one
  // south is never shutdown, and its address is changed first
  changeAddress(&sensorSouth, 0x23);
  delay(10);

  digitalWrite(WEST_SHUTDOWN, HIGH);
  changeAddress(&sensorWest,0x25);
  delay(10);

  digitalWrite(EAST_SHUTDOWN, HIGH);
  changeAddress(&sensorEast, 0x27);
  delay(10);

  digitalWrite(NORTH_SHUTDOWN, HIGH); // NORTH maintains default address

  // init all sensors
  initSensor(&sensorNorth);
  initSensor(&sensorSouth);
  initSensor(&sensorWest);
  initSensor(&sensorEast);
}

// Return the distance reading from the given direction
double getDist(int direction) {
  switch (direction) {
  case NORTH:
    return sensorNorth.readRangeSingleMillimeters();
  case SOUTH:
    return sensorSouth.readRangeSingleMillimeters();
  case WEST:
    return sensorWest.readRangeSingleMillimeters();
  case EAST:
    return sensorEast.readRangeSingleMillimeters();
  }
}

// return 1 if there is a wall, 0 if there is not a wall
int detectWall(int direction) {
  if (getDist(direction) <= WALL) { return 1; }
  else { return 0; }
}

#endif

And this is the test code I'm running:
#include "distSensors.h"
#include "Wire.h"
void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  setupSensors();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("NORTH: "); Serial.println(getDist(NORTH));
  Serial.print("SOUTH: "); Serial.println(getDist(SOUTH));
  Serial.print("WEST: "); Serial.println(getDist(WEST));
  Serial.print("EAST: "); Serial.println(getDist(EAST));
  delay(100);
}

getDist returns 0.0 for every sensor except for sensorSouth.
Any help would be greatly appreciated, thanks!

When coming out of hardware standby (reset) you need to provide time for the internal MCU in the VL6180X to boot up. Add a short delay between your HIGH and your changeAddress. Only a couple of milliseconds should do it.

After changing the i2c address, is that address stored in the sensor? Should it be set every time at startup? The pololu module has the recommended 47k resistor for gpio0/ce. When you put a 5v signal on that line the sensor might be damaged. That means at this moment all of those sensors might be broken. The module has a level shifter for sda and scl, but not the gpio0/ce pin. You should change the Arduino pin between output/low and input.

Might want to read: http://www.st.com/content/ccc/resource/technical/document/application_note/b4/f0/79/ec/ca/54/45/07/DM00114403.pdf/files/DM00114403.pdf/jcr:content/translations/en.DM00114403.pdf

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Pin Mapped Wemos D1 R1
I want to ask about Wemos d1 R1. Can I use those pins connected for different sensor?
For example I use pin D5 and D13 for switch and push button, or I use pin D7 and D11 for two different sensors.
Thanks.

well, D7 and D11 seem to be the same physical GPIO on the ESP8266, so, no, you probably can't use D7 and D11 for two different sensors

I need 13 pins for sensors and actuators. I use wemos d1 R1 because the actuators have to be controlled by telegram. So, any idea what I have to do if I can't use some pins for two different sensors?

esp8266 only ever has about 8 pins you can use

8 pins or 11 pins?

Available GPIO pins are 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16 - so, yeah, 11, sorry (forgot to include Tx and Rx and GPIO16 - I never use those for obvious reasons) - note: I'm talking about GPIO pins, not the Dn pins, as you can see, D5 and D13 refer to a single GPIO (14) - in fact D11,D12,D13,D14, D15 are dupes of D7,D6,D5,D4,D5 respectively

depending on the type of sensor, however, you may have enough pins (e.g. you can, and do, put multiple DS18B20 temperature probes on one pin) - without knowing your full requirements, I'm guessing

the pinout of D1 R1 is unfortunate. R2 has it much better

I didn't know you could still send telegrams...

What do u mean? I will use all of pins to sensors and actuators (11pins). Could I still connect to telegram?

can i use TX pin to connect with sensor?

I would not recommend using TX as input. It outputs boot log at startup.


text:
Two power source for Arduino and a relay
In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.
If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)
If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

The uno can't provide enough power to power an ESP8266 reliably.  I suggest you power it from a separate source.
When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them.  Otherwise the circuits don't use the same definition of zero.

Use  a relay driver IC like ULN2003 to drive relay.
Here is a sample circuit diagram :


text:
Sampling and serial transfer
I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.
int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

P.S I am new to arduino.
--edit1>>
I am using Arduino Mega 2560.

You don't state what Arduino board you are using. Perhaps you should look for a board with native USB, such as a Arduino Zero, Teensy 3.2 or the like.

Don't post two questions in quick succession about the same topic. It just annoys people, and doesn't increase your chance of a good answer.

Probably the serial port is too slow:
Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.
So you have to increase the speed for the serial port.

Thanks for the reply.
I have a doubt. One symbol in my case is two bytes per sample, with header bits giving 22 bits per sample. Since I have an additional 'x', that amounts to 33 bits in all. I want to send some 10k such samples or 330kbits per sec(> 250kbits per sec, hence the issue?). So merely increasing the serial.begin parameter should show an improvement?

You mean that one symbol is 2 bytes (digits?) Since it is sent as ASCII. You can check easily by REDUCING the speed and see if you have less speed, than you know that (at least) the serial port is the bottleneck. But increasing takes just a few seconds to try either.

Well, I increased the rate to 1000k and I am still at 6k samples.

Than the only reason I can think of is that either the procesing of getting the sensor values, or the processing of the print (some kind of overhead) takes too long ...you can try timing measurements to see what takes up most time

Read this http://yaab-arduino.blogspot.se/2015/02/fast-sampling-from-analog-input.html


text:
Improper sampling of wave
I am using Arduino Mega 2560 to sample and serially send a square wave. I am using Processing 3.3.6 for logging the data to .csv file. I am receiving about 6k samples at the moment. When I try sampling a square wave, min= 0V, max=3V at 200Hz, the number of samples at the two amplitudes(at 0 and 3V) are not at all close by. What could be going wrong?
This is my Processing code:
//import the required libraries
import processing.serial.*;

Serial mySerial;
Table table;
String filename;

void setup()
{ //print(0);
  //set mySerial to listen on COM port 4 at 1000000 baud
  mySerial = new Serial(this, "COM4", 1000000);

  table = new Table();
  //add a column header "Data" for the collected data
  table.addColumn("Data");
  //add a column header "Time" and "Date" for a timestamp to each data entry
  table.addColumn("Time");
  table.addColumn("Date");
}

void draw()
{ print(1);
  //variables called each time a new data entry is received
  int d = day();
  int m = month();
  int y = year();
  int h = hour();
  int min = minute();
  int s = second();
  //int s_prev=0;
  char d1 = 'a';

  if(mySerial.available() > 0)
  { //print(2);

    //set the value recieved as a String
    String value = mySerial.readString();
    //check to make sure there is a value
    if(value != null)
    {
      String[] parts = value.split("x"); //returns an array with the 2 parts

      //print(parts);
      //print('\n');
      for(int i=0;i<parts.length;i++)
      {

        String Part = parts[i];
        TableRow newRow = table.addRow();
        //place the new row and value under the "Data" column
        newRow.setString("Data", Part);
        //place the new row and time under the "Time" column
        newRow.setString("Time", str(h) + ":" + str(min) + ":" + str(s));
        //place the new row and date under the "Date" column
        newRow.setString("Date", str(s + 100));// + "/" + str(m) + "/" + str(y));
      }
    }
  }
print(4);}

void keyPressed()
{ print(5);
  //variables used for the filename timestamp
  int d = day();
  int m = month();
  int h = hour();
  int min = minute();
  int s = second();
  //variable as string under the data folder set as (mm-dd--hh-min-s.csv)
  filename = "data/" + str(m) + "-" + str(d) + "--" + str(h) + "-" + str(min) + "-" + str(s) + ".csv";
  //save as a table in csv format(data/table - data folder name table)
  saveTable(table, filename);
  exit();
}

This is my arduino code:
int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

Why have you asked two questions about this in quick succession?

In the previous one, I wanted to know about sampling and sending faster. Here, I want to know if I am sampling correctly.

You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.
That's not how you sample signals.
Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously.  Then when (and only when) a sample set has been captured do you send that data through serial.
If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending.  Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.

Thanks. I see where I went wrong. Would using the free running mode of the ADC serve my purpose better?

As long as you attach an interrupt to it to read each sample, yes.

Suppose I take a sample and send it serially within the ISR function, that would make all my samples equally spaced in time right?

As long as the serial sending takes less time than the time between samples, possibly. Sending serial from inside interrupts takes special care since it itself is interrupt driven.


text:
Digital Band pass filter arduino 1100-1300 Hz
For a project I need to design an digital band pass filter. I started of with this in Matlab:
wch=1100*2*pi;
wcl=1300*2*pi;

sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
sysd=c2d(sys,9615,'tustin')

so I got this values:

3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

Then I rewrote it to:
y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

and so I put hoped that this arduino script should do the Job:
#include <TimerOne.h>

float out;

float second_filt(float x0) {
  static float y1=0;  // y[n-1]
  static float y2=0;  // y[n-2]
  static float x1=0;  // x[n-1]
  static float x2=0;  // x[n-2]
  float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

  // Shift values
  y2 = y1;  // Shift y[n-1] to y[n-2]
  y1 = y0;  // Shift y[n] to y[n-1]
  x2 = x1;  // Shift x[n-1] to x[n-2]
  x1 = x0;  // Shift x[n] to x[n-1]
  return y0;
}

void setup() {
  Timer1.initialize(32); //Initialize timer with a period of 32 us
  Timer1.pwm(9,0); // Use pin 9 for PWM
}

void loop() {
  if (isTime()) {
    out=second_filt(analogRead(0));
    Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
  }
}

bool isTime(){ //Checks if 300 us elapsed since the last call
  static unsigned long t0=0;
  static unsigned long t1=0;

  t1 = micros();

  bool res = (t1-t0)>300;

  if (res) {
    t0 = t1;
  }
  return res;
}

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.

You may have trouble getting this to work on an ATmega-based Arduino, especially if floating point which must be emulated in software.  If you encounter difficulty you might consider one of the more recent Teensy series boards which have a more capable processor and a faster ADC as well.

You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).
For the mathematical power function, you should use the math C library. See library explanation. To include it, use:
#include <math.h>

The power function has the following prototype:
double pow(double x, double y)
Returns x raised to the power of y.

However if you only need to write a float/double in exponential format, you can use
3.01e-8

You have more than one problem here...

3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

I don't quite understand your Mathlab code, but there is something wrong
with this transfer function. The denominator can be rewritten as
(z + 1)2. Thus there is a double pole at
z = −1, i.e. at the Nyquist frequency. An infinite gain at
Nyquist is not what you expect from a bandpass filter.

y[k] = 3.01*10^-8*u[k] - 3.01*10^-8*u[k-2] - y[k-2] - 2y[k-1]

This is implementing the transfer function
3.01 × 10−8 (z2 − 1)/(z2 + 2 z + 1),
which is not the same as the one written above: mind the
parentheses.

float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2;

As explained in Michel Keijzers’ answer, the constant should be written
3.01e-8. Also, you can save one multiplication by writing it as
float y0 = 3.01e-8*(x0 - x2) - 2*y1 - y2;

if (isTime()) { out=second_filt(analogRead(0)); ... }

You cannot expect to get a uniform sampling time with analogRead(), as
your timing will depend on how long your program takes to get trough the
loop, which is data dependent and affected by interrupts.

sysd=c2d(sys,9615,'tustin')

I assume 9615 is the expected sampling rate, which translates to
104 µs between samples. This is the time it takes for the ADC to
perform one reading. You cannot achieve this rate if you do computations
in between the readings.
Here your best option is to configure the ADC in free-running mode. In
this mode it will take one sample every 104 µs, and you will
achieve the desired sampling rate. You should also do the filtering in
parallel with the readings, and have the CPU and the ADC work
concurrently instead of sequentially. For implementing this, you will
first have to read the datasheet of the ATmega328P powering your Uno.


text:
Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?
I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware.
Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

Not an exhaustive list. Most advantages will be subjective.

UECIDE - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
PlatformIO (Available as plugin for Atom editor, MS Visual Studio and Eclipse IDE) - Automatic library updating, one ini file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
Arduino IDE for Visual Studio - For those who like VS?
Arduino Makefiles - More like old-school command-line coding, Linux-style development. Not an IDE.
Eclipse - Another quite popular IDE outside Arduino world.
Atmel/Microchip Studio 7 - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.

VisualMicro is a powerfull addon to Visual Studio 201x (no command line needed and intellisense work). That's the best solution for ESP/arduino developpement in my opinion. The free version is really complete to make tests.
VisualGDB is also a good tool to debug (JTAG necessary) but only for ESP tool chain (arduino could be added is future release said in the forum...).

For example, Eclipse IDE with Sloeber plugin is much better than Arduino IDE. You have all the features of Eclipse (coloring, error highlighting, auto-complete, open declaration ('drill down' to libraries), ...*). And every project has own settings (board settings, port, programmer ...). And the Arduino IDE buttons Upload, Verify, Session Monitor are there and the Arduino toolchain too.
*... projects management, version control, TODO lists, outline, ...

I have a very bad experience of ECLIPSE at school last year. Lot of parameters hard to adjust and too much bugs... Visual studio (and code version) are robust days after days.


text:
MEGA I2C and interrupts on 0,1
Looking at the pinout for the Arduino MEGA:

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.
If I'm using an Adafruit I2C 16x2 RGB LCD Shield connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

No, there is nothing you can do.
Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.

I think there 2 other INTs that are brought out to pins as well, and then 2 more that are not, if PCINT won't meet your needs.

There are other INT pins for the MEGA I'm now using one of them. I haven't heard of PCINT though, I'll look into it.


text:
Why is Arduino Pro Mini not powering this LED?
First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.
As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.
I removed the button from the equation and just tried to power the LED with the Mini. No go.
It's a blue LED, so the resistor (100) was chosen assuming a forward voltage of 3.3V and current of .02A. I've tested the resistor and LED combo with JUST the battery pack, and it lights up bright like it should.
I have a 9V battery running into RAW (I've also tried a 6V pack). I had pin 2 as an output with digitalWrite(HIGH), running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. I've switched pin 2 to analogWrite(255), still nothing. I have tried connecting it to VCC instead. Nothing.
However, writing HIGH to the onboard LED works fine, so I can see that the sketch is indeed running.
I've verified the LED polarity. I have tried a different Pro Mini. Nothing. It's a Pro Mini 328P according to the stamp on the back, which Google says runs at 5V and 16 MHz.
Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.

Do you have this in setup()?  pinMode (yourLEDpin#, OUTPUT);

I do indeed:
pinMode(2, OUTPUT);
pinMode(ledPin, OUTPUT);

If it doesn't even work with Vcc, then maybe the battery is dead. What voltage do you measure across it?

Sadly, I do not own a multimeter, so I can't directly test the battery or arduino pins.
Indirectly though, I don't think the battery is dead. It does power the LED in a simple circuit when the mini isn't involved, and when I hook up the mini, it powers on and starts running the sketch, as evidenced by the onboard LED behaving as expected.

maybe you have 3.3v pro minis, whose output won't light up a resisted blue LED

Nope. It turns out the problem is that I'm an idiot.

Thank you both though for trying to help.

This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.
Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.


text:
NodeMCU not responding AT after blink app
I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.
I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

the Blink program replaced the AT program

@Juraj How can I put it back?

download the AT firmware binary from Espressif site. On Windows you can use Espressif Flash Download Tool to flash it. On Linux use esptool.py. https://www.espressif.com/en/support/download/at?keys=&field_type_tid%5B%5D=14

Done, thanks! Can you add this as an answer, people who has the same problem may see it easier :)

If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from Espressif download page and flash it with the Espressif Flash Download Tool (Windows) or with esptool.py.


text:
C++ Adding Two 16 bit binary numbers together
I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: int binaryOne[16] and int binaryTwo[16]. Originally,
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

are the values declared. Then, the user has the option to change these values using buttons that I implement before the Solution() function. So, once the used gets to the Solution() function, the numbers may be stored as:
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

This is what I have so far:
void Solution() {
  /*
    Rule of binary addition:
    0 + 0 = 0
    1 + 0 = 1
    0 + 1 = 1
    1 + 1 = 1 and carry = 1
   */
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Solution");
   lcd.setCursor(0,2);

    int a[16] = binaryOne[16];
    int b[16] = binaryTwo[16];
    int i = 0;
    int remainder = 0;
    int sum[32];

    while(a[16] != 0 || b[16] != 0){
      sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
      remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2;
      a[16] = a[16] /10;
      b[16] = b[16] / 10;
    }
    if(remainder != 0){
      sum[i++] = remainder;
    }
    i--;
    while(i>=0){
      lcd.print("%d", sum[i--]);
   }
   return 0;
}

I believe I am doing something wrong with calling the arrays since I am renaming them to a[16] and b[16] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

Why not just turn the array bits into an int number, and then add them?

int result1 = (a[15]<<15) | (a[14]<<14) | ... (a[2]<<2) | (a[1]}<1) | a[0];

do the same for result2.  Probably better if both are unsigned int.

then  unsigned long = result1 + result2;

@CrossRoads I need to output the solution as a binary number, sorry if I was not clear.

You say "I am renaming them to a[16] and b[16]", but int a[16] = binaryOne[16]; does not rename the array. When declaring an array, you have the option to initialize the array with a curly-braced list of values, or a string literal. Your code won't compile.

lcd.print(result, BIN)

@josecanuc I apologize, I added more description of the binaryOne and binaryTwo ints above for clarity on what I meant.

It doesn't change the fact that int a[16] = binaryOne[16]; does not rename the array or copy the array from binaryOne to a. int a[16] declares an array of 16 ints. binaryOne[16] doesn't refer to anything, because binaryOne is defined as an array of 16 ints, indexed from 0 to 15.

You're making a mountain out of a molehill.
You're trying to manually manipulate binary digits in an array, but C can already manipulate binary digits. Everything is binary already - you just need to represent it as such.
All you need to do is convert the contents of your array into an actual number, then do simple mathematics on that number.  One of the simplest ways of doing that is to shift the bits into a variable:
For instance:
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

uint16_t binOne = 0;
uint16_t binTwo = 0;

for (int i = 0; i < 16; i++) {
    binOne <<= 1;
    binOne |= binaryOne[i];
    binTwo <<= 1;
    binTwo |= binaryTwo[i];
}

Now you can add them together, since they're just numbers:
uint32_t result = binOne + binTwo;

And you can output it as binary:
Serial.println(result, BIN);

If you want to convert back into an array again (why?!) you can just do the opposite as before:
bool resultBin[32];

for (int i = 0; i < 32; i++) {
    resultBin[i] = (result & (1 << (31-i))) ? 1 : 0;
}

it is probably a school assignment

I tend to think things are a lot harder than they actually are unfortunately haha. I don't know why I didn't see this easy solution. Thank you!

Read the part of my answer that starts with: "And you can output it as binary..."

@Majenko Oh duh, it was right there, sorry. I will check your answer as accepted. I really appreciate your help!

A few issues here:

The way you “rename” the arrays is wrong, and furthermore there is no
point in doing such renaming.
There is no reason to divide by 10 (ten, in decimal) within your
code: as everything you do is binary, the number ten has nothing to
do with what are trying to accomplish.
While doing the addition, you forgot to loop over the bits.
You shouldn't return 0 in a function of type void. In fact, you
shouldn't return any value.

Fixing those issues should give you something similar to this:
void Solution() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Solution");
    lcd.setCursor(0, 2);

    // Compute the sum.
    int sum[16];
    int remainder = 0;
    for (int i = 0; i < 16; i++) {
        int s = binaryOne[i] + binaryTwo[i] + remainder;
        sum[i] = s % 2;
        remainder = s / 2;
    }

    // Print it.
    for (int i = 15; i >= 0; i--) {
        lcd.print("%d", sum[i]);
    }
}

Note that there is no point in computing a 32-bit result if you can only
print 16 bits: just accept that the computation is done modulo
216, just like a 16-bit ALU would do, or the unsigned int
data type in the Arduino.
Of course, the whole idea of doing the computation one bit at a time is
highly inefficient. See Majenko's answer for a more idiomatic and
efficient way of managing numbers bit-wise in C and C++.


text:
What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?
Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

You musrt be kidding! You present part of a schematic whose only completely shown component is one single resistor and you ask about its purpose!

What's the use?!!

@curd you can check arduino uno schematic for more detail on this. I particularly wanted to know about it so i cropped it out.

@Andyaka I am just curious how this works.

@Gahlot: this information belongs into the text of the question.

@curd updated !

Its a pulldown resistor!
Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.
They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.
The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.

How do you know?!?! It's connected to an input that can be an analog input. Therefore the resistor could just as well be the lower part of a voltage divider, it could be part of a RC filter, or anything else...

@Curd based on the fact its got a label for USB Boot Enable, sounds digital to me

it is a digital pin only.

@Timmy Hadwen: that's likely but without further context just an assumtion.

@Gahlot: why didn't you tell that in the question?!? and still then you should tell, or better, show more about the signal at that line.

I will keep that in mind from next time. :)

Pin 13 of the USB interface chip is connected to RESET line of the ATMEGA328 MCU. I would guess (also from "USB boot En" label) that pressing/issuing board reset gives the USB interface an interrupt (INT7), such that USB bootloader gets activated and the ATMEGA328 can start loading firmware code over USB. The resistor is a pull-down resistor ensuring LOW signal, and its value shouldn't matter much. However, there is a capacitor (C5) which provides a short pulse to the interrupt line. This is not the best way to form a digital signal and initiate an interrupt, but the RC should be long enough, so I would expect that if 100k is used, the cap can be much smaller than 100n as in 1k case.

i have seen a 100k resistor connected in pull up configuration though that's another topic. Can you explain your answer in more detail?


text:
Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04
I am new to Arduino and I am making a Walking Quadruped using BotBoarduino as microcontroller.
I want to install an Ultrasonic Sensor HC-SR04 so that it will stop when an obstacle is detected.
I have connected the sensor to Arduino UNO. RX-TX of both the boards are cross-connected. Now I have written this code for UNO:
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.println(distance);

  delay(200);
}

And I am doing this on BotBoarduino:
int byteRead;

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

void loop() {
  while (Serial.available())
  {
    byteRead = Serial.read();
  }

  if(byteRead >= 10)
  {
    walk();
  }
  else
  {
    stand();
  }
}

Whenever distance = 10 or above, let it walk. Else stop.
But it's not working. It's not stopping on obstacles. Sensor is doing its work perfectly, but I think Botboarduino is not getting the values.
Any idea guyz?

you need to look at the output of your Serial.println and what you are receiving in,   if the distance is 40 it is printing a '4' and a '0'   then you are reading in a single byte, which would give you an ascii 4 which in decimal is 34    so you will never get a byte that is less then 10 (0-10 are all non printable characters)

You have a misconception, how the Serial interface works.
The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.
Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for Serial.println()) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading while() loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable byteRead is overwritten on every while() loop cycle.
Then there is the format, in which you can send data through Serial.

Binary data: Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use Serial.write() on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
ASCII-encoded data string: You are using Serial.println(), which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value 10 you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function atoi())

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with Serial.println(), There will never be a value, that is under 10.
So now you have 2 options:

Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
Send the variable as ASCII-encoded data with Serial.println() and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.

Thanks! I just changed Serial.println(distance) to Serial.write(distance). Now it is sending the exact value.


text:
How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform?
Like make for not ESP Arduino target, is there a CLI command like esptool.py to upload in the hardware ?
I've seen makeEspArduino but seems to be not trivial ?
What about espressif ESP32 component ?
Is Visual Micro Arduino CLI (Command Line Interface) tool mature ?

Have you looked at https://github.com/arduino/arduino-builder/wiki/Doing-continuous-integration-with-arduino-builder

Thanx Craig. I'll have a deep look...

Easiest answer: Use PlatformIO. (Yes this answer is technically an advertisement, but it is the correct solution here.).
Why not the others?

makeEspArduino is dependent on GNU make, hard to make modification to, hard to get support for when something goes wrong
Visual Micro Arduino is Visual Studio extension, thus native to Windows

Why PlatformIO?
On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.
Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.
To create a new project, you'd do
user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

To compile from CLI, you just have to execute the run target:
user@somefolder/$ pio run

To upload you'd just
user@somefolder/$ pio run -t upload

With optional --upload-port=/dev/ttyUSB0 or alike. Updating wirelessly over ArduinoOTA is also supported.
Video: https://www.youtube.com/watch?v=EIkGTwLOD7o
Documentation: http://docs.platformio.org/en/latest/

Thanx a lot Maximilian Gerhardt for this complete answer


text:
how to send data to Adafruit Bluefruit Feather (32u4) over bluetooth?
Sup yo.
I have my Adafruit Bluefruit Feather all wired up.  It's lovely.  I've got it responding to commands over the USB serial, activating an array of octocouplers.  It's terrific.  Here's the thing though.  I need to talk to it wirelessly.
I can only pair it (MacOS) the Adafruit Bluefruit LE Connect app.  It doesn't show up in my Bluetooth preference pane.
$ ls /dev/tty.*  shows /dev/tty.Bluetooth-Incoming-Port and the Arduino IDE can see it.  Unfortunately the word Incoming is right there in the middle of that port name.  Sending commands through the Arduino serial monitor doesn't seem to do anything.
The Bluefruit connect app appears to be able to send commands over something called UART but my board doesn't respond to the stuff that works over USB serial.
How do I talk to this board over Bluetooth?

The “UART” being referred to is the Nordic UART GATT Service. This is not a serial port or USB connection. It is a high level BLE protocol that simulates a serial port via the Bluetooth connection.
In order to connect to the device from your Mac you’ll need to write some C or Obj-C. I’ve done this for Windows, but not a Mac, so I’m afraid I can’t give you detailed instructions. However, the source code for the iOS Adafruit Bluefruit LE Connect app you’re using is open source and should be a good starting point.
Be warned of a few things though.

You’re going to have to learn a bit about the BLE protocols and standards. It’s not exactly for the faint of heart.
Apple throttles the speed/throughput of BLE for their iOS devices (as does Android) to protect battery life. I don’t know if they apply the same throttling to their laptops. You may not be able to achieve a satisfying data rate if you’re looking to create a high throughput “data pipe”.  With Win10 and the Bluefruit LE I was able to achieve 40 bytes every 30ms. You’ll likely be limited to 20 every ~30ms.
If you’re looking to just send some occasional text (maybe AT style) commands to the device via BLE though, you won’t come close to those limitations.

gosh thanks dude.  it sounds like a lot more trouble than it's worth.  i'm just going to do a salvage run to another project that can actually do a bluetooth serial.

It depends on what you need. If you just need to send & receive some text at a low rate, not much trouble at all. If you need a lot of throughput, then yeah... it’s a bit of a headache. You’ve got to remember that BLE stands for Bluetooth Low Energy. It’s designed to conserve battery life.

First you should do some research on just what Bluetooth LE is.  First and foremost, what it is not, is a serial port.
In fact the BLE specification has no concept of serial ports, not like the old Bluetooth 2.x SPP specification.
Yes, you can use it like a serial port, but the point I am making is there is no GATT profile for serial data transfer. Every module manufacturer has their own way of doing it, so it's down to your application to implement that method (usually using libraries provided by the manufacturer). You can't present BLE as a serial port (COM3, /dev/rfcomm0 etc).
Sure, you could write a daemon that connects the MFG's custom method to a PTY and make it look more like a serial port (and such a thing may already exist in the community for some devices), but it will only ever work with that device and never any other device. There is no serial - there is only serial emulation and it's specific to the device. If it were standard no doubt someone would write a driver for it - like SPP of Bluetooth 2.x. But with GATT you just don't get that standard facility.
BLE is intended for sending short packets of data back and forth using minimal power. Many manufacturers have chosen to create a profile that can be used in a similar way to a serial port (in that you send data through a virtual "pipe"), however you require special software to interface with it. And, since there is no standard, and manufacturers just don't talk to each other, the software is specific to the device you are talking to.
If you are directly programming a BLE chip itself with your own firmware there is nothing to stop you from implementing your own protocol for serial data transfer and writing an application, driver, daemon, whatever, for communicating with that custom firmware. The same thing stands though: whoever wants to use it will require your specific application to communicate with it.
The only people who want to use BLE for serial are people like us. Everyone else (that's 99.999% of the market) uses it for what it is intended - connecting sensors and HID devices to mobile phones etc. That's why all the GATT profiles are for such things as heart rate, blood sugar levels, cycle speed, etc.
So no. You can't use it like a serial port. It's not a serial port. The only foolproof way (and the way to which I have resorted in the past) is to create a USB dongle that exposes a CDC/ACM interface to the computer, and contains a BLE module that is capable of communicating directly with a similar BLE module through its own proprietary profile (the one I use has a "transparent UART" mode when two modules are paired together). The MCU in the dongle then forwards data between the computer and the BLE module.

@RubberDuck I think you misunderstood what I was saying there. Yes, you can use it like a serial port, but the point I am making is there is no GATT profile for serial data transfer. Every module manufacturer has their own way of doing it, so it's down to your application to implement that method (usually using libraries provided by the manufacturer). You can't present BLE as a serial port (COM3, /dev/rfcomm0 etc). Sure, you could write a daemon that connects the MFG's custom method to a PTY and make it look more like a serial port, but it will only ever work with that device and never ...

... any other device. There is no serial - there is only serial emulation and it's specific to the device. If it were standard no doubt someone would write a driver for it - like SPP of Bluetooth 2.x. But with GATT you just don't get that standard facility.

Only works with Nordic though. Like I said, it's manufacturer specific as there is no standard.

lol thanks for the involved answer.  it sounds like this board is just not the right board here.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Linking Mulitiple Arduino's
I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.
Each Nano will run a basic collection of switches and LED displays.
Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.
The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.
What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?
Also, what would be the limitations on speed with this sort of com setup between the boards?
If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

running independent programs .... your description says otherwise

I would use SPI. It uses 4 pins on slaves and 3 pins on master plus one pin on master for every slave (slave select). You can use ICSP header 2x3 connector for firm connection.

but then the slaves can't use SPI as master (for LCD).

a serial ring communication library exists, but there if one arduino fails the entire communication stops

You could use I2C if the distances are short. For longer distances RS485 is the (wired) norm. Or use one of the many wireless technologies around. nRF24L01+ is cheap and well supported. Or ESP8266 and WiFi if you can't use SPI.

Could you clarify your specifications? When you say the information gathering should happen "at the highest possible speed", it's difficult to come up with a solution, since you may be unwilling to make certain compromises in speed that would make the system work better as a whole. So first set the goal/target data rate and work from there. For an Uno to monitor the joystick, button inputs, and multiple 7-segment displays, your communication speed must be limited. If all your devices are on a common bus, each slave will have to provide it's data in turn, etc.

One advantage of RS485 is that you can make 3 independent buses using the UARTS 1, 2 and 3 of the Mega, and still keep UART 0 for debugging. Then you have 3 times the throughput, as the UARTs can work in parallel.

@jsotola Each Arduino will have an individual program that runs a specific part of the "ship" for instance Nano1 runs the power systems. All of it's lights and switches are independent. But it will need to receive information from other systems (for instance Nano 3 which runs the shields systems) that can tell it if "power" is being used by other ship systems, which it can then output on it's "power level" displays.

@josecanuc The entire system is built into a roughly triangluar shaped "tabletop" for lack of a better word that has a base length of 6.5' and a height of 3.5'. The distance between the MEGA and the farthest processor is no more than 3 feet. My response to Code Gorilla explains the joystick usage in my project but I can provide more details if necessary. Any delay in processing that can be mitigated is acceptable. I just don't want them to turn the "shields" to full and the "engine power" display to remain unchanged for several seconds.

Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.
So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.
Connecting the joysticks via interrupts will allow a more responsive system, can you do this?
Is an Arduino even the best platform for this?  What about an ESP32 or PI?
You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.

I will have to answer your questions in multiple comments due to character limit.

The different Arduinos are used because each micro-controller will be running a separate panel of the project and have it's own program running. (Nano 1 for instance only deals with the ships Power systems. It accepts input data from the Mega when other ship systems are activated. It runs 3-12 segment bar-graphs, 7 indicator LED's, and 6 toggle switches. The processor only needs to calculate current system power usage and emergency states, so not a heavy processing load.)

Arduino Unos along with a USB shield are used to control each joystick individually and change the "position" of the ship, which is displayed via 3 separate 7 segment displays. Additionally the Uno's program will deal with weapons fire, in particular counting how many missiles were fired, and display that number on a second 7 segment display. (this is a pilot and co-pilot setup, co pilot takes control of ship positioning during docking procedures) Also the toggle switches and indicator lights for thrust and weapons are each dedicated to the Uno's.

so as far as the number of Arduino's, I think I've minimized it well enough. I don't want the program complexity and length to overwork any individual processor, or overflow the memory capacity.

Simply making all the different components and systems connect via expansions to a single mass processor doesn't seem to be the solution, but perhaps I'm wrong, might need more clarification on how that could work.

I definately think the joysticks should be via interupts, but I'm not sure quite how to do that, would love more detail on that process. (At the moment I will be using the low cost thrustmaster USB $16 joysticks and a usb shield for the UNO. I am still waiting on shipping for the shield to begin proto testing this. Have some tutorials on the interface but very difficult to figure out so far)

Arduino may not be the best platform for this, but it's what I have, and I've made the investment in it so I want to see if it's possible. I keep scaling back the project to make it feasible, so I'm willing to try alternate approaches, but not really wanting to just ditch arduino and start from scratch again. It's for my kids so if it's got lots of cool lights and switches their happy (but for me I want them to be able to grow this project in the future and really make something of it).

How does a "star network" work? where could I learn about that?

it is a star topology. master in the middle and a line to every slave.

@Juraj, ok I was planning to do something like that. I was going to have the MEGA occupy the middle and use it to link all the other boards, using it as the master for them all. How might you connect the boards to do that? Would it be best to simply allow the slave boards to run their programs, and transfer relevant data to the Mega, who would then return relevant data to the appropriate slaves? what would that program look like? what would the wiring look like?

read my comments under the question

It sounds like the dashboard for a cobra mk3.  By eliminating processors you remove the need to communicate between them, and the timing issues you will need to handle.  Adding in ICs that do very specific tasks will reduce the program complexity further.  The shield displays can be linked via a serial to parallel converter, means one pin connects to the IC an that controls the whole display.  All the buttons can trigger the same interrupt and then you can scan the buttons to see which on was pressed, again this is a serial to parallel IC.


text:
Arduino Square Wave Phase Shift by 270 degrees
I am using this code to generate a square wave with Arduino and shift it by 90 and 180 degrees. However, this code is not able to shift it to 270 degrees. Could you please suggest how may I modify the code so that it supports a 270 degrees square wave phase shift operation.
void setup() {
  pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
  pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B
  // Both outputs in toggle mode
  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
  // CTC Waveform Generation Mode
  // TOP=ICR1
  // Note clock is left off for now
  TCCR1B = _BV( WGM13) | _BV( WGM12);
  OCR1A = 0;    // First output is the base, it always toggles at 0
}
// prescaler of 1 will get us 8MHz - 488Hz
// User a higher prescaler for lower freqncies

#define PRESCALER 1
#define PRESCALER_BITS 0x01
#define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

// Output phase shifted wave forms on Arduino Pins 9 & 10
// freq = freqnecy in Hertz (  122 < freq <8000000 )
// shift = phase shift in degrees ( 0 <= shift < 180 )
// Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC
/// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.
int setWaveforms( unsigned long freq , int shift ) {
  // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.
  unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave
  ICR1 = clocks_per_toggle;
  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision
  OCR1B= offset_clocks;
  // Turn on timer now if is was not already on
  // Clock source = clkio/1 (no prescaling)
  // Note: you could use a prescaller here for lower freqnencies
  TCCR1B |= _BV( CS10 );
}
// Demo by cycling through some phase shifts at 50Khz
void loop() {
  setWaveforms( 40000 , 0 );
  delay(1000);
  setWaveforms( 40000 , 90 );
  delay(1000);
  setWaveforms( 40000 , 180 );
  delay(1000);
}

The answer is in the code you posted, in a comment: “To do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC”.

I tried to understand that statement and it doesn't make much sense to me. Could you please help me modify the code or understand the statement? @EdgarBonet

Not your own code?

No, I took it from here: https://electronics.stackexchange.com/questions/174656/avr-arduino-output-2-pwm-waveforms-with-90-degree-phase-shift?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

It sounds like it means "Invert the waveform, and do a 90 degree shift".

setting the FOC bit forces an output compare once regardless of OCR value, effectively causing a 'premature' toggle. This inverts the waveform in the long run. FOC are the last 2 bits (6, 7) in the TCCRB register, FOCxA/B by macro

@mystery could you please advice on how can I modify the code to be able to do the operation. Sorry I am really new in this space

The Arduino can only shift across a range of 180 degrees in CTC-mode using a 16 bit Timer. If you shift one channel to 90 degrees (other OCR set to 1, not zero) and then add a logic-inverter, you'll get the equivalent of 270 degrees as mentioned by Edgar Bonet.
As for using FOC (forced output compare), Edgar B. is again correct. It's possible to preset a channel as inverted, then perform the shift with an OCR set for 90 degrees -- you won't need an extra logic inverter. But this method is not for someone new. You'll want an O-Scope handy to make it work (and some time to study FOC and CTC mode-12).
I think it easier to use a single section from a 7404 hex-inverter to flip your 90 degree shifted waveform to 270.
Search for "Phase Shift Square Waves" and you'll find a VIDEO (as of 2022) for an example project that uses FOC tactics to create runtime-adjustable phase shifts on an Arduino. Perhaps you'll see a way to make an easy code change for the flipped-phase you want...
FWIW stockvu


text:
serial communication between arduino to 89c51 with gsm
I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

Use I2C, SPI or any other protocol?

There is always software serial.

The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

Use a software serial, this will work only for low speed transmissions. You can download this as a library.
Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.


text:
Series of µsec pulse generation using Arduino Due
I'm working on a project in which I need a series of very accurate pulses containing 2 shots in every pulse. The pulse should have 100µsec on time followed by 300ms off time. But when I'm programming the Arduino Due I'm getting random pulses of non-uniform width. But when I'm trying the same code in microsecond range I'm getting perfect wave.
Here is the code that I'm using

#define LED 8 // Pin designated to give out the pulse
int cycles = 2;  // No. of times you want it to give pulse
int high = 100; // High time in microseconds
int low = 300;  // Low time in milliseconds
int i = 0;
int univ_cycle = 10;

void setup() {
  // put your setup code here, to run once:
 pinMode(LED, OUTPUT);
 Serial.begin(9600);

}
void loop(){
  for (i ; i < univ_cycle; i ++){
  pulse();
  delay(100);
  }
}
void pulse() {

  // put your main code here, to run repeatedly:
  for(int counter = 0;counter < cycles;counter++){
  digitalWrite(LED, HIGH);
  delayMicroseconds(high);
  Serial.println("ontime");
  digitalWrite(13, LOW);
  Serial.println("offtime");
  delay(low);
  Serial.println(counter);
  }

}

Here is the image of the waveform in microsecond setting

Here is the wavefrom that we got in millisecond setting

I would like to know how can I get the similar wave in microsecond also.

I would suggest as a start removing those Serial.println calls. They will make complete nonsense of any timing you attempt to do.

Look into using one of the 16bit timers. What do you mean with “two shots in every pulse”?

@Gerben I assume he means ___-__-______-__-______-__-_____

@Majenko silly me. I should have looked at the scope output.

@Gerben Can you please suggest me how to use 16-bit register?

Setup the timer to call an interrupt service routine every 100us. In this routine increment a counter. Set the output high when the counter is 0, and low otherwise. Reset the counter when you reach 3000 (i.e. 300ms). This is for a single pulse. For the double pulse you’d have to add some extra code. I’d suggest checking the timer1  library for setting up the timer interrupt.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Configuring Timers to Add One More 50kHz Square Wave
I am generating two 50kHz square waves, but I would like to generate three square waves. I have problems with generating the third square wave.
Basically, I need to configure the timer bits so that I can get the third square wave.
Here is the code I need to modify for the third square wave:
// This code demonstrates how to generate two output signals
// with variable phase shift between them using an AVR Timer

// The output shows up on Arduino pin 9, 10

// More AVR Timer Tricks at http://josh.com

void setup() {
  pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
  pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B

  // Both outputs in toggle mode
  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );

  // CTC Waveform Generation Mode
  // TOP=ICR1
  // Note clock is left off for now

  TCCR1B = _BV( WGM13) | _BV( WGM12);

  OCR1A = 0;    // First output is the base, it always toggles at 0

}

// prescaler of 1 will get us 8MHz - 488Hz
// User a higher prescaler for lower freqncies

#define PRESCALER 1
#define PRESCALER_BITS 0x01

#define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

// Output phase shifted wave forms on Arduino Pins 9 & 10
// freq = freqnecy in Hertz (  122 < freq <8000000 )
// shift = phase shift in degrees ( 0 <= shift < 180 )

// Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC

/// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.

int setWaveforms( unsigned long freq , int shift ) {

  // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.

  unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave

  ICR1 = clocks_per_toggle;

  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision

  OCR1B= offset_clocks;

  // Turn on timer now if is was not already on
  // Clock source = clkio/1 (no prescaling)
  // Note: you could use a prescaller here for lower freqnencies
  TCCR1B |= _BV( CS10 );

}

// Demo by cycling through some phase shifts at 50Khz

void loop() {

  setWaveforms( 50000 , 90 );

  delay(1000);

}

What are the problems you are having? The code you posted doesn't look like it makes any attempt at a 3rd signal.

@josecanuc Exactly, there are only two signals generated. I just wanted to show what I am currently using to generate two signals. Need to modify the code to be able to generate third signal

what is the relationship between the three signals?

@jsotola They are supposed to be 90 degrees different. 1st signal - 0 degrees, 2nd - 90 degrees, 3rd - 180 degrees. Ideally, i would need a 4th which is 270 degrees, but one problem at a time.

On the Uno, you only have two PWM outputs per timer. If you need more, you will have to configure a second timer. If you need them to be synchronized, you will have to use Timer 0, but then you loose the Arduino timekeeping functions (millis() and co.) If you use Timer 2, you can preserve those functions, but you may have imperfect synchronization.


text:
Help with my project on motors using the Arduino Board
I was given the task of being able to drive two motors in the forward direction, able to drive two motors in the reverse direction, and they must be able to drive each motor independently. I was wondering if anyone can give me directions, advice, or tips on the coding for this task. All I know is that:
if(switchState == HIGH){
digitalWrite(motorPin, HIGH);
}
else{
digitalWrite(motorPin, LOW);
}
}
I know this code makes the motor turn on and off with the high and low, but what type of code do I use to make it work at a certain speed, and to move independently?

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. Please revise your question showing your work and findings so far. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

given the task .... is this school work?

There are plenty oft tutorials in the web. Google and follow one of them

you can use PWM function of digital pins (analogWrite())to control the motor speeds as desired.


text:
Sending dynamic data to webserver
I am trying to send data to a php file via http GET method.
I am able to send static data but I am unable to send dynamic data.
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(9, 10);

char inchar;
int ledPin = 13;
int sensorPin = A0;
int sensorValue = 0;

boolean gs = true;
boolean es = true;
boolean ss = false;

void setup()
{
  gprsSerial.begin(9600);
  gprsSerial.println("AT+CNMI = 2,2,0,0");
  Serial.begin(9600);
}
void loop()
{
   currentMillis = millis();
   if(gprsSerial.available()>0)
  {
    inchar = gprsSerial.read();
    if (inchar == '#')
    {
      delay(10);
      inchar = gprsSerial.read();
      if (inchar == '1')
      {
        Serial.println("System Enabled");
        ss = true;
        snd_msg(0);
      }
      else if (inchar == '0')
      {
        Serial.println("System Disabled");
        ss = false;
        snd_msg(1);
      }
      delay(10);
      inchar = gprsSerial.read();
      if (inchar == '1')
      {
        Serial.println("Geofence Enabled");
        gs = true;
        snd_msg(2);
      }
      else if (inchar == '0')
      {
        Serial.println("Geofence Disabled");
        gs = false;
        snd_msg(3);
      }
      delay(10);
    }
  }
    gprs();
    delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}
 void snd_msg(int a)
{
  gprsSerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  gprsSerial.println("AT+CMGS=\"+918148090646\"\r"); // Replace x with mobile number
  delay(1000);
  if ( a == 0)
  {
    gprsSerial.println("System Enabled");
  }
  else if ( a == 1)
  {
    gprsSerial.println("System Disabled");
  }
  else if ( a == 2)
  {
    gprsSerial.println("Geofence Enabled");
  }
  else if ( a == 3)
  {
    gprsSerial.println("Geofence Disabled");
  }
  delay(100);
   gprsSerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  gprsSerial.println("AT+CNMI = 2,2,0,0");
  delay(1000);
}
void vibra_sensor()
{
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  for(int i = 0; i < 5; i++)
  {
  if (sensorValue > 500)
  {
    es = true;
    break;
  }
  else
    es = false;
  delay(500);
  }
  delay(1000);
}
void gprs()
{
  vibra_sensor();
  Serial.println("Config SIM900...");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // attach or detach from GPRS service
  gprsSerial.println("AT+CGATT?");
  delay(100);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"www\"");
  delay(2000);
  toSerial();

  // bearer settings
  gprsSerial.println("AT+SAPBR=1,1");
  delay(2000);
  toSerial();
  // initialize http service
  gprsSerial.println("AT+HTTPINIT");
   delay(6000);
   toSerial();

   // set http param value
 **gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=ON\"");**
   delay(5000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
   gprsSerial.println("AT+CNMI = 2,2,0,0");
  delay(1000);
}

What I've Tried
1.) Saving URL in a string
String URL = "adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=";
    URL += ss;
    gprsSerial.println("AT+HTTPPARA=\"URL\",\"+URL\"");

Doesn't Work
2.)Attaching values using print statement
gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=");
gprsSerial.println(ss+"\"");

3.)Entering value directly in URL
gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="+ss+"\");

Error
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

I'm using an arduino uno and a sim 900a GSM module.
QUESTION
How do I send dynamic values for gfence, sstatus, estatus?
I am also using a messaging service, the code is included. The help I need is in the gprs() function.
The data I need to send is,
gfence from gs
sstatus from ss
estatus from es

How does this not work? The GPS module returns an error? The HTTP server returns an error? Your PHP script returns an error?

it is unclear what you mean by static data and dynamic data.

boolean ss = false; ..... URL += ss; .... ..... binary 'operator+' ............... you cannot concatenate a boolean value True  .... you can concatenate a string value "abc123" or "True"

+URL is not a valid URL. The syntax highlighting should have given you a hint.

You should split it up:
gprsSerial.print(F("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="));
gprsSerial.print(ss);
gprsSerial.println(F("\""));

Note the use of print on each part up until the last part which is the only one that uses println in order to terminate the line.
Also note the use of the F() macro to reduce the wastage of RAM that string constants cause.

F() for one character?

Sure. Frugality is key with 2k ram

ok, I eventually googled that it is has no overhead in code

@Juraj I could have switched to Serial.println('"'); (i.e., use a single char), but that would most likely have confused the OP. Best to keep things simple.


text:
Change RF Receiver Frequency by Antenna Length
This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino.
I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?
Thanks in advance.

No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.


text:
Powering an Arduino Uno using 2 (or as few as possible) AAA batteries
[Background] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.
Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?
Thanks for the help

The 8 MHz version of the Arduino Pro Mini, while nominally powered at 3.3 V, should work fine down to 2.5 V according to the ATmega328P datasheet.

The problem here is not an Arduino-equivalent processor, but powering the servo.  Servos for micro/indoor aircraft are available for operation at lower than normal voltages in the 3-4v range.  An ATmega will run on that voltage as well.  So solve your servo power problem first.

I've got a page about power saving.
My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.
If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.

The flight of an amateur rocket doesn't last very long. I wouldn't advice the Arduino to take a nap in mid flight.

Well in that case any battery that can last the distance would do. :)


text:
Parsing HTTP get response to extract values
Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:
Linked

T+CIPSEND=4,50

> GET /ard/sensor.html HTTP/1.1
Host: localho
SEND OK

+IPD,4,351:HTTP/1.1 200 OK
Date: Sat, 07 Apr 2018 01:22:58 GMT
Server: Apache/2.4.9 (Win32) PHP/5.5.12
Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
ETag: "72-56937eec1c277"
Accept-Ranges: bytes
Content-Length: 114
Content-Type: text/html

<p> Relay1 = 1#  </p> </br>
<p> Relay2 = 0#  </p> </br>
<p> Relay3 = 0#  </p> </br>
<p> Relay4 = 1#  </p> </br>
OK

OK
Unlink

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low
Note : # is supposed to be the separator
and here is my code:
    #include <SoftwareSerial.h>

const int LED_PIN = 13;

String ssid = "ABC";
String password = "a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {

  Serial.begin(9600);
  ESP8266.begin(9600);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

  ESP8266.println("AT+RST");
  ESP8266.println("AT+CIOBAUD=9600");
  delay(1000);

  if (ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  ESP8266.println(cmd);

  delay(4000);

  if (ESP8266.find("OK")) {

    Serial.println("Connected!");

  }

  else {

    connectWifi();

    Serial.println("connect to wifi");
  }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());

Byte R[ ] = ESP8266.read () ;
Serial write (R[ ]);

//    if (readString.indexOf("Relay1=1">0))
{
    Serial.write("found");
}
  }

}

Any suggestions ?

why do you send it as html like text? send 1001

First of all, I would avoid using the String class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with strstr() or sscanf(), to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.
Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:
static void parse_relay_callback(uint8_t index, uint8_t value)
{
    Serial.print("parsed: relay ");
    Serial.print(index);
    Serial.print(": ");
    Serial.println(value);
}

You will have to replace this with whatever is appropriate for your
application.
Then here is the parser:
static void parse_relay(char c)
{
    static const char templ[] = "RelayI = V#"; // I: index, V: value
    static uint8_t pos, index, value;
    char expected = templ[pos++];
    if (expected == 'I' && c >= '0' && c <= '4')
        index = c - '0';
    else if (expected == 'V' && (c == '0' || c == '1'))
        value = c - '0';
    else if (expected == '#' && c == '#')
        parse_relay_callback(index, value);
    else if (c != expected)
        pos = 0;
}

You just feed it one character at a time, with something like:
while (ESP8266.available())
    parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:
parsed: relay 1: 1
parsed: relay 2: 0
parsed: relay 3: 0
parsed: relay 4: 1


text:
ESP8266 doesn't connect to WiFi
I'm using an ESP8266 with the following pin configuration and it doesn't connect to my WiFi. The blue light on the ESP module is on and my LED is on. That's it.

VCC - 3.3v
GND - GND
CH_PD - 3.3v
GPIO 0 - GND
GPIO2 - LED

I'm using a 1,000 mah 3.7 LiPo battery for this.
Here's my Arduino code. I'm following a tutorial from nyl.io.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid     = "sukkaa";
const char* password = "123456789123";
const char* host     = "www.sukkzzesp.tk"; // Your domain
String path          = "esp\light.json";
const int pin        = 2;

void setup() {
  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);
  Serial.begin(115200);
  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: " + WiFi.localIP());
}

void loop() {
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  client.print(String("GET ") + path + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond
  // read response
  String section="header";
  while(client.available()) {
    String line = client.readStringUntil('\r');
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print(".");
      if (line=="\n") { // skips the empty space at the beginning
        section="json";
      }
    } else if (section=="json") { // print the good stuff
      section="ignore";
      String result = line.substring(1);
      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success()) {
        Serial.println("parseObject() failed");
        return;
      }
      // Make the decision to turn off or on the LED
      if (strcmp(json_parsed["light"], "on") == 0) {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      } else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
  }
  Serial.print("closing connection. ");
}

Pls help me with this error. Thanks.

with io 0 LOW esp8266 goes into bootloader mode

Hi Juraj I removed GPIO 0 from GND and still the same results. Not connecting and theres a small hum coming from the esp chip

you power it with 3.7 V?


text:
Reading data from potentiometer with MISO and MOSI on same pin
I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.
I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.
Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

I’d not use the SPI bus for this but use the (bitbanged) Arduino function shiftOut and shiftIn.

You need to do a little conversion:

Connect the SDI/SDO line to MISO on the Arduino.
Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.
Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).

Awesome I will give this a try later!

The solution worked, while digging through the datasheet I found this page SPI Examples . I followed this and it worked perfectly!


text:
How to program an SSD1322 display?
I'm new to programming. I would like to change the characters on an SSD1322 OLED display. Here are the photos.
Is this possible with an Arduino Uno? Is the program of the display in the display or in the Mega 2560?
Thanks for your help!

An SSD1322 is just a graphical OLED display, like the SSD1306 and many others. It just displays what it's sent. Whatever that thing is it's plugged in to is what is generating the graphics that are being displayed.

OK thanks for your answer,
so if I understand the program that manages the display is on the pcb or there is the 2560?

It's whatever the display is plugged into. It may be that 2560, but I don't know what that board is, so can't comment.

on the 2560 card there is an ISP connector
http://liedson.fr/1.jpg
is it possible to connect an arduino uno to read the program that is in the 2560?

no, it is most likely copy protected

yes that is possible, but I have a second blank pcb without a program,
I just wanted help with the procedure.
must it connect the pcb 2560 by the IPS with an arduino uno?
I can also pay the person who will take the time to help me work on it!


text:
What is the tool to send file to SPIFSS on ESP8266/32?
Is there good tools (IDE, CLI or IDE addon) to send file via USB port to SPIFSS internal espressif ESP hardware SoC ?

Have you read the manual? http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html

yes, but it's a LOT faster to load it over wifi.

The mkspiffs tool creates bin from file system data (or extracts data from bin).
SPIFFS bin is uploaded with esptool over USB or with espota over WiFi. It can be uploaded with the sketch binary in one command.
Example:
esptool.py -p /dev/ttyUSB0 write_flash 0x0 sketch.bin 0x300000 spiffs.bin

The IDE plugin adds SPIFFS upload to Arduino IDE Tools menu.


text:
How to write Arduino API code in VL53L1X?
I'm trying write code for the VL53L1X on Arduino,  but I didn't get the VL53L1X registers. How to access them and how to measure the data in VL53L1X? Can anyone help me?

And the datasheet says what?

what model of arduino is the VL53L1X Arduino?  ... which manufacturer makes it?

He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.
ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.
Sparkfun have just released a library. It's much smaller but, like the Polulu library for the  VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.
https://github.com/sparkfun/SparkFun_VL53L1X_Arduino_Library/blob/master/src/SparkFun_VL53L1X_Arduino_Library.cpp
There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.
It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).

Majenko, there is no proper data sheet. The programming details are described in the code. Partially.


text:
Can external power supply above current limit lead to errors/shutdown arduino?

I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.
Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?
If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?
Also, how much current can I safely drive through the VIN Pin?
Thanks!

If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.
The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.
So theoretically the chip should keep running fine all the time regardless of what happens with the power.

Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


text:
Cannot connect to database Ethernet Shield
I am using an LDR sensor to store its readings into the database. My code is as follows:
  #include <SPI.h>
  #include <Ethernet.h>

  const int ledPin = 13;   //the number of the LED pin
  const int ldrPin = A0;  //the number of the LDR pin

  byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

  IPAddress ip(192, 168, 1, 177); // ip of arduino

  char server[] = "192.168.1.105"; // IMPORTANT: If you are using XAMPP you
  will have to find out the IP address of your computer

   // Initialize the Ethernet server library
   EthernetClient client;

   void setup() {

   // Serial.begin starts the serial connection between computer and Arduino
   Serial.begin(9600);
   pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
   pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
   // start the Ethernet connection
   Ethernet.begin(mac, ip);

 }

Next, I wrote the setup code:
 void loop() {

  int ldrStatus = analogRead(ldrPin);   //read the status of the LDR value

  //check if the LDR status is <= 300
  //if it is, the LED is HIGH

  if (ldrStatus <=300) {

   digitalWrite(ledPin, HIGH);               //turn LED on

   }
 else {

digitalWrite(ledPin, LOW);          //turn LED off

}

// Connect to the server (your computer or web page)
if (client.connect(server, 80)) {
client.print("GET /info.php?"); // This
client.print("value="); // This
client.print(ldrStatus);
client.println(" HTTP/1.1"); // Part of the GET request
client.println("Host: 192.168.1.105");
client.println("Connection: close"); // Part of the GET request telling the
server that we are over transmitting the message
client.println(); // Empty line
client.println(); // Empty line
client.stop();    // Closing connection to server

}

else {
// If Arduino can't connect to the server (your computer or web page)
Serial.println("--> connection failed\n");
}

// Give the server some time to recieve the data and store it. I used 10
seconds here. Be advised when delaying. If u use a short delay, the server
might not capture data because of Arduino transmitting new data too soon.
delay(1000);
}

The problem is that when I try connecting to database, it gives a database connection failed. I have crosschecked the ip address of my computer and have even logged into it using xampp to check if it is working.
However, the problem is still persistent.

Which shield are you using?

The problem is in your info.php script. It has nothing to do with the Arduino.

you get "--> connection failed" in Serial Monitor?