Where does the Arduino core include the name of the sketch? I'm trying to look through the Arduino core to find where "mySketch.ino" is included or implemented. In 'Arduino.h', the prototypes void setup(void) and void loop(void) are defined, in 'main.cpp', setup(void) and loop(void) are called, but I'm not sure where 'main.cpp' or any other related files makes a reference to the sketch.

Where does this occur?

Compilation doesn't start with the Arduino.h or the core files; rather, it starts with your own sketch, "whatever.ino". Your .ino file includes Arduino.h into the compilation which makes references to core modules. That compilation leaves many references to to be satisfied, and itself satisfies several - setup() and loop(), for two. At link time, the linker is told to read not only your compiled module(s), but also the compiled core files, from which it can extracts the modules required to satisfy references made by your compiled code. Then it combines your module, and those modules required by it, into the load file that avrdude uploads to the Arduino.


How to organize my Arduino projects' structure for easy source control? It's been a long time I've been looking for a good answer to this question.

Typically, any Arduino project but the simplest one will include:

The main source code file MyProject.ino
Libraries specific to the project (MyProjectLibrary1.h, MyProjectLibrary1.cpp...)
Third-party libraries (generally free open source, added manually to Arduino libraries directory)
Schematics, PCB diagrams
Documentation
...

All this makes it hard to keep the whole code and doc of one project under Source Code Management (e.g. on Subversion, Git or GitHub).

Managing source control of your project means managing the version of all files used by the project including 3rd-party libraries.

Now for a single project, I need to define a directory structure that:

Includes all project files as described above
I can entirely commit to a Source Code Management tool (including 3rd-party dependencies)
I can checkout anywhere on my hard drive and build the project from there (does it have to be a single location as imposed by Arduino IDE)
I can zip into a self-contained archive that I can send to a friend for him to build as easily as possible (no extra manual download)

What I find particularly tricky with Arduino projects is the management of external libraries dependencies. Java projects developers have maven repositories for that and that helps a lot in managing all external deps. But we don't have an equivalent system for Arduino libraries.

I would be interested to know how other Arduino project makers deal with these aspects in their own projects.

Also note that I am open to changing my development process, including my IDE (currently I use Eclipse with the Arduino plugin most of the time, and then I ensure my projects can also work directly with the Arduino IDE).

My way of organizing an arduino project is quite simple, all my project are git repositories so that there is at least the following:

project/

project.ino
Makefile

I have a preference using my favorite editor and a Makefile which I have crafted to work against most use cases (and I even improved on that one that I'm going to share soon).
For the libraries, I prefer to keep them as their own repositories and use git submodule to include them to the project. As many libraries written by the community are shared as git repositories, that's a good generic solution. Then, within the Makefile, I just have to add the libraries path I want to include in the LOCALLIBS variable.
Though, for some projects, it makes sense to encapsulate the libraries into a hardware abstraction layer library crafted for the project, then I prefer to use a path such as:

project

project.ino
Makefile
project_hal_lib

library1
library2
library3
…

Though, with arduino 1.5.x a new way to specify libraries is offered, that will offer a way to create and build arduino projects the same way we already do with pipy and virtualenv in python, i.e. you define the set of libraries you need and they get downloaded.


Lockup while evaluating Wire.requestFrom function (Arduino) I am currently working on a Arduino project that combines an InertiaOne IMU sensor board (from Atmel), with an Arduino UNO and two motors driven by a Makeblock driver board. All sensors communicate using I2C, with different addresses. My issue is that the program runs just fine for a while (everything between 1 second and 2 minutes), but suddenly lock up inside the Wire.requestFrom-function that handles I2C communication. More specifically, I believe that the code hangs at one of these points in the Wire library (the code is a direct copy):

...
// wait until twi is ready, become master receiver
while(TWI_READY != twi_state){
    continue;
}
...
// wait for read operation to complete
while(TWI_MRX == twi_state){
    continue;
}

As far as I know, there are only two units that utilise I2C in the system, both of which are embedded onto the InertiaOne circuit board. What I find very strange is that reading these two sensors works just fine when no motors are running, but that the problem occurs when the motors are activated. My first reaction was to use separate power supplies for the motors and sensor board since the issue could have been caused by a dip in the voltage and a reset of the sensor board, but without any change of result.

I am running out of things to try, and do simply not have the required understanding of I2C and embedded systems to see what exactly the issue is. Could it simply be that some of my parts are faulty, or am I perhaps overlooking something?

The Wire library has an issue in the lines you posted, that if an interrupt is lost, it will stay in that loop forever. There are two things you could do to fix this:

Stop the interrupt from being lost (ie. fix electrical problems)
Use a library that has a time-out.

For the electrical issues, I would make sure you have pull-up resistors from SDA and SCL to +5V - typically 4.7k (for each one), but that would depend a bit on whether the device already has them. Also make sure you have decoupling capacitors on the Vcc lines as appropriate.

For the software side, there is an alternative library (master only) at
Arduino I2C Master Library.

I haven't personally needed to use that library, as with pull-up resistors and short cable runs, I haven't had problems with the Wire library. However if things are marginal you may well find that it helps.


MQ7 Readings are too high I am currently trying to learn how to use my MQ 7 CO Standalone to read CO in the air around the sensor. Currently Im using this circuit using my Arduino Uno. I get results of 900-1000. Here's a Fritzing Schematic on my setup.

Currently this is the code I am using on the arduino:

[code]

int mqx_analogPin = A0; // connected to the output pin of MQ-X

void setup(){
  Serial.begin(9600); // open serial at 9600 bps
}

void loop()
{
  // give ample warmup time for readings to stabilize

  int mqx_value = analogRead(mqx_analogPin);
  Serial.println(mqx_value);

  delay(100); //Just here to slow down the output.
}

I'm following the setup from this Instructables:
http://www.instructables.com/id/Smoke-Detector/?ALLSTEPS

However his readings are around 150-200ppm outside. I'm unsure how to reach these values since im following basically everything from the guide. Does anyone any experience with a MQ7 sensor?

I've been reading I need to preheat the sensor but I can't find any circuit that clearly shows how to preheat an MQ7 sensor or find any code for the arduino.

Using of this sensor is a bit more complicated than that. You must cycle through 60 seconds of heating and 90 seconds of measurement cycles, during heating you need to provide 5V on its heater pins, during measurement you need to provide 1.4V, so you'll need transistor or some other PWM-controlled current limiter (Arduino pin can't provide enough current for sensor heating).
I've tried to explain all details and calibration process here: https://www.instructables.com/id/Arduino-CO-Monitor-Using-MQ-7-Sensor/


I'm trying to make a program which you choose an angle I'm trying to make a program which you choose an angle, and it tells you it's respective Sin, Cos and Tan. But, I can't figure out why all of the angles I use have the same answer (Sin 0, Cos 1 and Tan 0. Can someone help me out?

#include <math.h>
double angulo;
double seno;
double cosseno;
double tangente;
double rad;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {

 Serial.println("Programa para calcular sen, cos e tg");
 delay(1000);
 Serial.println("Digite o angulo");
 angulo = Serial.parseInt();
 rad = angulo*0,0174533;
 seno = sin(rad);
 Serial.println("Seno");
 Serial.println(seno);
 cosseno = cos(rad);
 Serial.println("Cosseno");
 Serial.println(cosseno);
 tangente = tan(rad);
 Serial.println("Tangente");
 Serial.println(tangente);

}

You have written

rad = angulo*0,0174533;

But, C++ uses the american decimal notation:

rad = angulo*0.0174533;

Thus, you have been multiplying angulo by zero every time.


RFID stops working when I place the servo I've successfully implemented Door Unlock system described in this tutorial.
At first I used Arduino Uno and RFID RC522 Reader and MG90S Micro servo.

When I used Arduino Uno with Arduino Pro Micro for arduino ATmega32U4 5V/16MHz, the RFID reader stops working after plugging the servo.
Since Arduino Pro Micro have only 5V output, I used resistors to downgrade 5V to 3V in order to poser the RFID reader. I used same output 'vcc' to select 5V for the servo and 3V converted to the reader.

The problem is that each component works perfectly independent of each other, however, when I place them together they stop working.

Use a 3.3VDC regulator for your RFID board a small boxed DC-DC buck converter will be easiest, if linear use an LDO type. Ideally also use a level shifter on your data lines. This could be a resistor voltage divider or zener diode clamp at the most basic, FETs or a dedicated IC is a bit more involved but gets better results.


Does the ESP8266 somehow remember wifi access data? Today I did some tinkering with an ESP8266, trying out OTA and writing a webserver. To find an error, I reduced the sketch to just the following lines:

#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200);
  server.on("/", []() {
    Serial.println("Sending response...");
    server.send(200, "text/plain", "Hi there!");
  });
  server.begin();
}

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

Notice that there is no code to connect to a Wifi network. However, the chip still connects to my local, WPA2-secured, network on every boot. I can ping the chip, my browser can get the "Hi there!" message via http, the Serial message gets printed.

How is this possible? Does the ESP8266 somehow retain the Wifi information, maybe because of some old OTA data that was not completely overwritten?

I'm using platformio. Here's my entire platformio.ini:

[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino

I posted the compile and upload log here: https://pastebin.com/BtGrFZiu

Yes, normally the last WiFi credentials will be saved in flash and the ESP8266 loads this data on bootup and reconnect to the last known WiFi. See https://github.com/esp8266/Arduino/issues/2843#issuecomment-334250100:

the SDK stores some info, including the wifi credentials, in a sector of the flash.
That sector is kept between flashings to allow for a quick startup after update. On boot, before your sketch is executed, the SDK will retrieve the wifi credentials and attempt a quick connection.

This behaviour can be controlled by using the function WiFi.setAutoConnect(autoConnect) as documented in https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#setautoconnect. This in turn calls the Espressif SDK function wifi_station_set_auto_connect (API reference)

In short: This is normal behaviour. If you want to make sure that your ESP8266 does not connect to any WiFi unless you tell it do it explicitly, call WiFi.setAutoConnect(autoConnect) at the beginning.
Edit: From within the firmware code, you can use system_restore. The documentation says that it would reset WiFi related data. This should destroy previous settings. The function can be included from https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h within Arduino-ESP8266. I have not tried this myself nor can I say that it actually erases security-critical information from flash though.

Or, as you also have found out, hard-erasing the entire flash will purge the WiFi data with absolute certainty. This can be achieved by using esptool.py with the erase_flash option, e.g. python esptool.py -p COM6 erase_flash. Then you can flash the new firmware which will not use previous WiFi settings (but will probably open up the default access point again).
Then there's also ESP.eraseConfig which erases only the relevant flash sectors.


Use ESP8266 as WiFi client connected to Arduino Pro Mini So i'm trying to use the PubSubClient Library on my arduino mini pro, but I'm connecting to the internet via wifi using an ESP8266.

Using a mini means I have to use software serial to connect to the ESP, but I've ran into a problem. I can't find anywhere such as ESPWiFiClient to use with the examples from the PubSubClient library where they use EthernetClient.

Is there any available libraries that can emulate EthernetClient with an ESP module over software serial?

Ditch the Pro Mini.  Upload your Arduino code to the ESP directly. There's a GitHub repo with the details. ESP for Arduino IDE has a ton of libraries. I'm sure you'll find it there.

But if you're bent on using the Pro Mini,  you'll have to use AT commands over serial to control it or flash a custom firmware into the ESP using Lua or something. And Pro Mini can use its hardware serial just like a Uno does.


Breadboard Arduino not loading sketches I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.

I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

GND -> Breadboard GND
5v -> Breadboard + rail
TXO -> IC pin 2
RXI -> IC pin 3
GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.

Any ideas on what might be the problem?

To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

you need to have a bootloader flashed on the chip
you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader
your programming software must use the same baud rate as the bootloader is expecting
you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.


Problem with passing string pointer from child to parent I am trying to pass a pointer to a const char * from a child to its parent, but I am clearly not understanding how to do this correctly. Here is the code which contains three classes:
1) parent
2) Alpha (child)
3_ Beta (child)

#pragma once
class Parent {
protected:
    char *childName;

public:
    Parent ( char* _childName ) {
        childName = _childName;
    }

    char *getChildName () {
        return childName;
    }
};

class Alpha: public Parent {
protected:
    const char* alphaName = "ALPHA";

public:
    Alpha (): Parent ( alphaName ) {
        Serial.print ( F ( "My name is " ) );
        Serial.println ( getChildName () );
    }
};

class Beta: public Parent {
protected:
    const char* betaName = "BETA";

public:
    Beta (): Parent ( betaName ) {
        Serial.print ( F ( "My name is " ) );
        Serial.println ( getChildName () );
    }
};

Alpha *alpha;
Beta *beta;
void setup () {
    Serial.begin ( 115200 );
    while (!Serial.availableForWrite ()) {}

    alpha = new Alpha ();
    beta = new Beta ();
}

void loop() {}

And here is the output I get:
My name is �

My name is �˵

The problem here is that alphaName and betaName are member variables. That means they are initialized during the Alpha and Beta constructors. However, the superclass constructor of Parent is always called first, before calling the child class constructors. Result: Parent::Parent(char *) is called with an uninitialized pointer.

Here is your code on the Compiler Explorer: https://godbolt.org/z/otAuQU
As you can see, Alpha::Alpha() compiles to the following:

call Parent::Parent(char*)
ldd r24,Y+1
ldd r25,Y+2
ldi r18,lo8(.LC0)
ldi r19,hi8(.LC0)

.LC0 is the string "ALPHA".

The solution here is to make the names static. That way, they are initialized before the parent constructor is called.

class Parent {
  protected:
    const char *const childName;

  public:
    Parent(const char* childName) : childName(childName) {}

    const char *getChildName () const {
        return childName;
    }
};

class Alpha : public Parent {
  protected:
    constexpr static const char *alphaName = "ALPHA";

  public:
    Alpha() : Parent(alphaName) {
        Serial.print(F("My name is "));
        Serial.println(getChildName());
    }
};

This compiles to:

ldi r22,lo8(.LC0)
ldi r23,hi8(.LC0)
call Parent::Parent(char const*)

As others have mentioned, pointers to string literals should always be const. The only reason this doesn't give an error is because the Arduino folks decided that it was a good idea to compile everything with -fpermissive ...
Mutating a string literal is undefined behavior, so an error.


Audio/Voice Recording Device I'd like to build a little voice recorder for my grandmother. She told me "I get a lot of idea when I'm driving but then I forget them. I want a necklace where I can just press a button and it'll record my voice and I can press a button and it'll stop recording." She wants each recording to save as a separate file. I was thinking of concealing a mini Arduino board or Rasberry Pi or something in a necklace, with a removable micro sd card. Or something like that. I just don't know where to start, I don't have much experience with this. Does anyone have any tips on what kind of device I could use or where to start? I suggested that she just have Siri take notes for her on her iPhone but she wants something around her neck, and she wants me to make it.

Try this amazing breakout board. Its all you need. SparkFun Voice Recorder Breakout - ISD1932

Moreover, If you thinking on letting that device talk back, try this: VoiceShield

Well, there is also an instructable for this, HERE. This Instructable will show you how audio input can be repeatedly added to a 512 byte buffer and then transferred to a SD card in real time. The audio file can be played back on a standard audio application or analysed byte by byte.


Attach headers to servo wires? I have these 3 wires coming from a servo motor. They're very thin and flimsy and despise staying in a breadboard.

Is it possible to add headers to these wires to make them easier to put in a breadboard? (Like the attached image) And if so, where would one procure such a thing?

What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them).

Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun).

You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much.

You could put some thicker heat-shrink over all three wires, to give additional stability.


How can I make my arduino start when a magnet is sensed, and stay running until the application determines it was to shut down My thought was to use a magnetic reed switch to turn on the arduino.  But how do I keep it running if the magnet is moved?  The idea is that the application will determine when it is ok to shut off the power to the arduino.

I don't want any power usage when the system is dormant since it could be weeks between magnetic triggers.

Doug

Put your Arduino into deep sleep and attach an interrupt to a pin that is monitoring your reed switch. Once triggered it can run your code before deep sleeping again


Why this code for ESP8266 goes into STA+AP mode? I'm using Arduino IDE 1.6 nightly with Generic ESP8266 Board.

Why this code runs in mesh mode instead of simply connecting to my wifi?
My goal is to test out MDNS, but so far I found this:

board connects to my wifi
but board also opens an ESP- access point
when connected to my wifi on my computer I cannot resolve http://esp8266-webupdate.local/update
when connected to the open ESP- wifi I can resolve http://esp8266-webupdate.local/update

To my understanding such code should just connect to my wifi and I would then be able to navigate to http://esp8266-webupdate.local/update, am I missing something?

output (note STA+AP)

Booting Sketch...
......
Connected, IP address: 192.168.1.20
Mode: STA+AP
PHY mode: N
Channel: 10
AP id: 0
Status: 5
Auto connect: 1

code

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

const char* host = "esp8266-webupdate";
const char* ssid = "myhomeap";
const char* password = "blabla";

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void setup(void){

  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

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

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  WiFi.printDiag(Serial);
  MDNS.begin(host);

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
}

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

It goes into STA+AP mode because your code is telling it to do that.

If you want it to just go into STA mode then your line:

WiFi.mode(WIFI_AP_STA);

should be

WiFi.mode(WIFI_STA);


How accurate the an attiny timer function I have an AT-Tiny (trinket) and I want to trigger LED on for 30 seconds every 24 hours. I'm using the timer library as follows

timer.setInterval(86400000, toggleit());

void toggleit()
{
  turnLightOn();
  delay(6000);
  turnLightOff();
}

How accurate will this be, if it's off by a few minutes each day that's fine, but will this drift over time? Also does it make a difference if I'm running it in 8 or 16 bit mode?

The on-chip systemclock is not very accurate. You can calibrate it to some degree but it also depends on the temperature and load of the MCU. You will need a high quality quartz oscillator as external clock source to reduce it. But it will still have a drift. Switching from 8-bit to 16-bit won't make a difference.

In your case an RTC sounds like the way to go.


Relays just switch ON and OFF on delay(), not on millis() I use fuzzy logic for the running time of relays, but the relays just switch ON and OFF at the interval of the delay() I put at the end of loop.
This is my code:
void loop () {
  ph = -180/100.0;
  hasilec = -1.2;
  unsigned long now = millis();

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph);
  Serial.print(" ");
  Serial.print(hasilec);
  Serial.print(" ");
  Serial.println(" ");

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1); //pHDOWN
  float pompa02 = fuzzy->defuzzify(2); //pHUP
  float pompa03 = fuzzy->defuzzify(3); //ABMIX

  long int pompa1 = pompa01 * 1000;
  long int pompa2 = pompa02 * 1000;
  long int pompa3 = pompa03 * 1000;

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa1);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa2);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa3);
  Serial.println("");
  Serial.println("");
  Serial.println("");

  pump_periods[0] = pompa1;
  pump_periods[1] = pompa2;
  pump_periods[2] = pompa3;

  for (int i = 0; i < jml_pump; i++) {
    if (now - pump_last_actuations[i] >= pump_periods[i]) {
      pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;
      digitalWrite(pump_pins[i], pump_states[i]);
      pump_last_actuations[i] = now;
    }
  }
  delay (20000);
}

The relay just switch ON and OFF on this delay delay (20000);.
What should I do?

Check the values of pompa1, pompa2, and pompa3 to see if they are always smaller than 20000 (I suspect they are).
The delay(20000) (why is it there anyway?) could well be messing up your timing of the toggling of the pump_states by always delaying longer than the values in pompa1, pompa2, and pompa3.
This would make the relays toggle every 20s (on every loop).


How to change the usb name of Atmel 32u4? I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.

I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.

On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.

The Arduino '32U4 bootloader, Caterina, can be found under hardware/arduino/bootloaders/caterina. It requires LUFA in order to build.

With the technical part aside, note that you are not allowed to use the USB IDs assigned to Arduino LLC with products you intend to distribute under another name. You will need to acquire your own vendor ID from the USB-IF if you want to do so.


How to check if a LED is on? I have a circuit board / device that can be in different states. It indicates in which state it is by turning on one of three LED's. Now I want to use an ESP8266 to tell me (over the network) the current state. What kind of circuit would I need for this? (I have thought about using photodiodes, but I would much rather solder something directly to the board)

If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266.  If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate level shifter or the appropriate optical isolator:


Servos and ultrasonic at the same time So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.

Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.

The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...

So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.

I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?

CODE :

#include <Servo.h>

#define ECHO 2
#define TRIG 7

 Servo servo;
 int distance;
 volatile long echoTime = 0;
 long trigTime = 0,sendTime = 0,timeServo = 0;
 bool scanning = false;
 byte servoDir = -1,servoAngle = 0;

void setup()
{
  servo.attach(12);
  Serial.begin(115200);
  pinMode(ECHO,INPUT);
  pinMode(TRIG,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

}
void loop()
{
  // SERVO

   if((millis() - timeServo > 10)){
     if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
     servoAngle += servoDir;
     servo.write(servoAngle);
     timeServo = millis();
   }

  // GETTING RESULTS
  if(echoTime > 0){
    distance = echoTime - trigTime;
    distance /= 58;
    echoTime = 0;
    trigTime = 0;
    Serial.println(distance - 8);
  }
  // SENDING PULSE
  if(millis() - sendTime > 20){
  digitalWrite(TRIG,LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG,LOW);
  trigTime = micros();
  sendTime = millis();
  }
}

 // INTERUPT
void echo_interupt(){
  echoTime = micros();
}

8cm is 233µs of sound travel time.  There and back again would be 466µs.  466µs, at 16MHz, is around 7400 instructions.

When an interrupt is triggered you don't get an instant response.  First the built in interrupt function is called. That then looks to see if you have registered an interrupt function.  It then calls that interrupt function.

All that takes time, and when you're working with microseconds it makes a big difference.

And then you have to go and get the current micros() value, which again takes time to do.

So it all adds up to a delay.  Not ideal.

For greater accuracy you should investigate using input capture which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received.  From that you can calculate a much more precise distance.

As for why you are getting strange results with the servos on?  Most likely because you are moving the receiving head while the pulse is being received.  I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.

Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.


Attiny85 code on Attiny84 I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile.
Im using Arduino UNO as ISP.

Error what i have:

WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
WDTCR |= (1 << WDCE) | (1 << WDE);
^
In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
             from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
             from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
             from WDT_Time.cpp:12:
WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
              ^
WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
   ^
WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
   sbi(PCMSK, PCINT3);
       ^
WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
   sbi(PCMSK, PCINT3);
   ^
'WDTCR' was not declared in this scope

There are slight differences between registers, register names and registers bit names:

WDTCR is named WDTCSR
PCIE doesn't exist in GIMSK as there are two IO ports, so there are two pin change channels: PCIE0 and PCIE1
and PCMSK is similar to PCIE. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.


How to reset ESP8266 wifi module I have programmed ESP8266 to make it accessible over the network using below program.

First Program

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

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

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

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

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

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();          //Handle client requests
}

It is working fine, What is the way to reset it to run below program? I wanted to send AT commands on serial monitor using below program which has been uploaded successfully but not responding AT commands on Serial Monitor, as ESP8266 is running above program and showing output of above program on running below program on Serial Monitor.

I want to reset ESP8266 so it responds to below program. What is the way ?

Connected to Moto
IP address: 192.168.43.115
HTTP server started

SecondProgram

#include "SoftwareSerial.h"

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

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(9600);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer
    Serial.write("Hello");
    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

You need to reinstall the AI Thinker AT firmware.

Here's how you do it: How to flash ESP8266 firmware update ESP-01 AI thinker

Last time I did it I used the esptool.py program, and used the ai-thinker-0.9.5.2.bin firmware (there's two versions on there, the default 115200 baud, and a 9600 baud variant).

On Linux I then used the command:

foo@bar:~$ ./esptool.py --port /dev/ttyUSB0 --baud 57600 write_flash 0 ai-thinker-0.9.5.2.bin
Connecting....
Detecting chip type... ESP8266
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 512KB
Flash params set to 0x0000
Compressed 520192 bytes to 165297...
Wrote 520192 bytes (165297 compressed) at 0x00000000 in 29.0 seconds (effective 143.3 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting...

This was, of course, with GPIO0 held LOW for programming mode (I actually use an adaptor with a programming switch that controls GPIO0), and for other operating systems you will need to change the port name to suit (COM3:, /dev/cu.usbmodem4873, etc).


Posting data to ASP web service from GSM using AT commands - where am I going wrong I'm using an Arduino uno with a SIM900 GSM shield.  I'm trying to connect the Arduino to my (ASP MVC) website.  I've written an API which i've successfully tested with postman, and whilst the GET Command works fine, I've had no success with POSTING data as yet.  Using the arduino to echo serial monitor input, I've done the following...

So, some setup commands

    AT+CGATT?
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    AT+SAPBR=3,1,"APN","internet"    (vodafone UK parameters
    AT+SAPBR=3,1,"USER","web"
    AT+SAPBR=3,1,"PWD","web"
    AT+SAPBR=1,1
    AT+SAPBR=2,1     (confirms i have an IP address)

i then do the following...

    AT+HTTPINIT
    AT+HTTPPARA="CID",1
    AT+HTTPPARA="PROIP","212.183.137.12"   (vodafone uk proxy settings)
    AT+HTTPPARA="PROPORT","8799"
    AT+HTTPPARA="CONTENT","application/json"
    AT+HTTPPARA="URL","http://mywebsite.co.uk/api/obs"
    AT+HTTPDATA=83, 10000    (gives the download command).
    {"SensorName": "TestSensor", "ObsValue": 31, "ObsDateTime": "2017-10-01T03:30:00"}
    AT+HTTPACTION=1

and I just get an "OK" back, no httpaction response, and no data stored on the database.

Is there anything I'm doing that is obviously wrong?  Does HTTPACTION come before the data?

Are there commands I can use to check the status of my http session on the GSM board? to confirm that my settings are correct?

Finally, I keep getting messages like

    +CREG: 1,"002A","0F48"

Always the 1 (presumably the CID i'm using), and always the 002A, but the final part varies.

Any help would be hugely welcome.  Thanks.

+CREG: 1,"002A","0F48"

That's the registration status. "1" is "Registered on your 'home' network", "002A" is your LAC (Location Area Code) and "0F48" is the Cell ID (CI).


Why does my LCD screen display white rectangles? I recently got an Arduino LCD screen. I tried connecting it to the UNO with the 10k potentiometer and all the needed equipment but all I got were white rectangles instead of characters. I have uploaded the hello world code but I saw no changes.

As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.


TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307 Been working on this project for some time now, like title states when I un-comment setSyncProvider(RTC.get) in the setup the program fails to get any of the Alarm.timerOnce to run.

I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.

#include <Wire.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

//#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
//byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
  prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
  ignPin = 7,     //  Igniter output pin D7
  solPin = 8,     //  Solenoid output pin D8
  genPin = 9,     //  Generator output pin D9
  tonePin = 11,   //  Tone output pin D11
  ligPin = 3,     //  Light sense pin A3
  intPin = 3,     //  Interupt pin D3 runs double bang

  runTime = 20,   //  minutes to run for

  state = 0;      //  state of operation

bool operate = false, // True if within operating time
   timeIsSet = false; // true if time till next opperation is set
double cur;

void setup() {
  Wire.begin();
  pinMode(13,OUTPUT);
  pinMode(ignPin, OUTPUT);
  pinMode(solPin, OUTPUT);
  pinMode(genPin, OUTPUT);
  Serial.begin(9600);
  //setSyncProvider(RTC.get);  //******************************************
  Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
  Alarm.alarmRepeat(20,0,0,OffAlarm);
  tone(tonePin, 31, 1000);
  randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

  OnAlarm();
}

void loop() {
  if ((analogRead(ligPin) > 30) && operate == true)
  {
    if (timeIsSet == false)
    {
      tone(tonePin, 58, 500);
      int randm = random(27,36);
      Alarm.timerOnce(randm,operation);
      Serial.println(randm);
      timeIsSet = true;
    }
  }
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

void operation(){
  tone(tonePin, 100, 1000);
  Alarm.timerOnce(12,after20m);
  digitalWrite(genPin, HIGH);
}

void after20m(){
  digitalWrite(genPin, LOW);
  Alarm.timerOnce(5,after5s);
  digitalWrite(solPin, HIGH);
  tone(tonePin, 494, 1000);
  timeIsSet = false;
}

void after5s(){
  tone(tonePin, 200, 1000);
  digitalWrite(solPin, LOW);
  Alarm.timerOnce(1,after1s);
}

void after1s()
{
  digitalWrite(ignPin, HIGH);
  Alarm.delay(500);
  digitalWrite(ignPin, LOW);
}

void OnAlarm() {
  operate = true;
}

void OffAlarm() {
  operate = false;
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  //Serial.print(operate);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Problem existed in the TimeAlarms library,

Q: How many alarms can be created?
A: Up to six alarms can be scheduled.
The number of alarms can be changed in the TimeAlarms header file (set by the constant
dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

so how I fixed it was to edit #define dtNBR_ALARMS 6  // max is 255 to #define dtNBR_ALARMS 14   // max is 255 in the TimeAlarms.h file.


How I can divide information stream from bluetooth hc-06? All good afternoon or evening. I am having a problem writing a sketch for Arduino using Arduino UNO and Bluetooth HC - 06.

My program does not divide the input stream of information into several variables. No matter how many variables I specify, they are considered as one.

Maybe I do not know all subtleties of the use of Serial.read(). Apparently from a sketch given below I get through Bluetooth two variables of color and var. A microcontroller perceives these two variables as one and as a result does not execute before him task. As a result we will be able to choose the color and change delay of blinking by this color.

If anybody knows how to correct this problem or can point me to a similar project I will be very thankful for any rendered help

const int rPin = 3;
const int gPin = 5;
const int bPin = 6;
int chosed_color;
int val;
int color;

void setup()
{
  Serial.begin(9600);
  pinMode( rPin, OUTPUT );
  pinMode( gPin, OUTPUT );
  pinMode( bPin, OUTPUT );

}

void loop()
{
while(Serial.available()>0)
  {
     color = Serial.read();
   if(color==1)
      {
       chosed_color = rPin;
      digitalWrite( rPin, HIGH );
      digitalWrite(rPin, LOW);
       return chosed_color;
      }
        else if(color==2)
      {
       chosed_color = bPin;
       digitalWrite( bPin, HIGH );
      digitalWrite(bPin, LOW);
       return chosed_color;
      }
         else if(color==3)
      {
        chosed_color = gPin;
       digitalWrite( gPin, HIGH );
       digitalWrite(gPin, LOW);
       return chosed_color;
      }
  }
if(Serial.available()>0)
{
  val = Serial.read();
}

      digitalWrite( rPin, HIGH );
      delay(val);
      digitalWrite(rPin, LOW);
      delay(val);
}

Your code have various issues.

This:

   if(color==1)
      {
       chosed_color = rPin;
      digitalWrite( rPin, HIGH );
      digitalWrite(rPin, LOW);
       return chosed_color;
      }

means that when you find a color, you exit loop() instead of reading the val variable.

Serial.read

Serial.read read only one byte. If you need to read an arbitrary integer, need Serial.parseInt or some elaborate solution. As it, you are only able to read one-digit integer values.

Worse, when you type "1" in the Serial Monitor, what the program received is the value 49 (the ascii code for char 1).

Also, you have to filter non interesting chars, like LF, CR, commas or whatever char you use as delimitir.

Please, read the excelent post by Majenko about Reading Serial on the Arduino.

Here a better version of your code. It is very basic and lacks all error checking, etc.

const int rPin = 3;
const int gPin = 5;
const int bPin = 6;
int pins[3] = {rPin, gPin, bPin};

void setup()
{
    Serial.begin(9600);
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
}

void loop()
{
    if(Serial.available()>0) {
        int color = Serial.read();
        int chosed_color = pins[color-1];
        digitalWrite(chosed_color, HIGH);
        digitalWrite(chosed_color, LOW);

        if(Serial.available()>0) {
            int val = Serial.read();
            digitalWrite(chosed_color, HIGH); // I suppose you want this
            delay(val);
            digitalWrite(chosed_color, LOW);
            delay(val);
        }
    }
}


Why was the Due retired? Looking at the Sparkfun comparison, it seems that the Due is by far the fastest of the Arduinos and has I/O capabilities similar to the Mega. So why was it retired with no obvious successor?

"Why was the Due retired?" - It is quite interesting that Arduino.CC never explained that. One would think, that a professional company or organisation places a notice in advance with at least a short explanation as to why.

Most of the Arduinos, that have been available on both projects (CC and ORG) have suddenly and without further notice or explanation been retired on CC (the exceptions being Uno and Mega 2560, the cash-cows), but are still alive on ORG.
It would seem, that either the "divorce" is proceeding or that the copyright case at the US court is not going as smoothly as Banzi hoped. Well, he could repeatedly "bend the truth" by claiming Arduino being completely his idea and design in front of the press (that never bothered to check the obvious facts), but laying such a claim at court is borderline criminal. (see also: arduinohistory.github.io and make your own opinion)
CC has still the biggest chunk of the overall community and also serves as the central nexus for developers. But it seems there is a lot of movement... some people move to Wiring (from which the Arduino IDE was forked), others to 3rd Party sites and yet others try out different  and newly emerging products (eg. Adafruits MCUs and Pi or the Renesas GR series).
ORG on the other hand seems to become the bigger (Arduino branded) hardware supplier and developer. CC has apparently out-sourced this to Intel and tries to live of royalties and "certification" fees (which is the central point where Banzi and Martino started to heavily and openly disagree).

"Why was the Due retired?" - Unless CC doesn't give an explanation, there is no real answer. A lack of interest is certainly not the reason.


UART ESP and MEGA2560 Could someone help me with some suggestions please?
Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :

LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

when it should display this:

LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

the code for ESP is this:

int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

the code for mega is this:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}

Solution to your problems.

Use println instead of print.
Change char c = Serial.write(Serial.read()); to char c = Serial.read();


What is a simple way to measure the ambient light? I want to install some LED stripes on my motorcycle, i.e. as brake light and indicators. I use WS2812 LED stripes which can be very bright - especially with many LEDs on at the same time.

I want to measure the ambient light so that in the bright sun I can light the LEDs with, let's say, 100%. But in the night maybe just with 30% intensity. I want to detect the ambient light to change the intensity.

I don't need high resolution and I don't need high speed. If the ambient light is measured i.e. once per second with 4 bit resolution that would be already good enough.

Which ambient light sensor (or photo diode or whatever) makes sense for this little project and how to connect it?
Does it make sense to use more than one light sensor for a better average ambient light value (just in case one sensor is in the shadow, another in the sun)?

I found these sensors form a Chinese supplier:

https://www.banggood.com/CJMCU-9930-APDS-9930-Digital-Proximity-And-Ambient-Light-Sensor-For-Arduino-p-1103139.html

https://www.banggood.com/GY-49-MAX44009-Ambient-Light-Sensor-Module-For-Arduino-p-1196674.html

But an I2C interface seems to be overkill for my simple project.

Any suggestions?

Perhaps a LDR and a 10k ohm resistor might work.

#define LDRpin A0
unsigned int LDRvalue = 0;

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

void loop(){
  LDRvalue = analogRead(LDRpin);
  Serial.println(LDRvalue);
  delay(1000);
}


Need help with a program for a button to change the display on an OLED display So I am programming an OLED display from my Arduino Uno. I am trying to have a button that switches the different words on the display. (The words are just placeholders for programs as of now.) My program has a button that changes a counter, and an if test to see what the counter is so it can display the appropriate word. The problem is, whenever I press the button, the display turns black and doesn't do anything anymore. When I start/reset the Arduino, it displays TEMPERATURE, but it should say TIME.

#include <OLED_I2C.h>

OLED  myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

//constants:
const int buttonPin = 2;

//variables:
byte oldButtonState = HIGH;
int screenNumber = 0;
byte buttonState = 0;

void setup()
{
  myOLED.begin();
  myOLED.setFont(SmallFont);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() { //myOLED.print formats with (string, text_placement,     pixel_location)
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // Test if the button is being pressed
  if (buttonState == HIGH) {
    myOLED.clrScr();
    myOLED.update();
    oldButtonState = buttonState;
    if (screenNumber != 2) {
      ++screenNumber;
    }
    else {
      screenNumber = 0;
    }
    //delay a little to avoid bouncing
    delay(200);
    }

  //Test for the screenNumber variable and change to the
  //according screen
  if (screenNumber == 0) {
    myOLED.print("TIME", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 1) {
    myOLED.print("TEMPERATURE", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 2) {
    myOLED.print("DIRECTION", CENTER, 16);
    myOLED.update();
  }
  else {
    myOLED.print("ERROR", CENTER, 16);
    myOLED.update();
  }
}

You have pinMode(buttonPin, INPUT_PULLUP); so I assume, you connected the button between pin and ground. With pull-up the pin will read HIGH if it is not grounded. If the button is pushed, grounding the button pulls it LOW. So you should test if the button is pressed with comparing to LOW.

We have this misleading idea in our heads that active is HIGH and not active is LOW. But you can see it this way:

button pushed down (low) is LOW
button not pushed is up (high) reading HIGH


One of the LEDs on my Arduino is very dim I made a vibration sensor using an Arduino. It is connected to an Android app. When the start button is pressed on the app, a red light LED turns on (stand by), and after 2 - 5 seconds, the red LED turns off and a green LED turns on (meaning the system is ready). The green LED turns off if the sensor detects a vibration. The green LED works perfectly. However, the red LED is always dim. I've tried testing the red LED separately, it works fine. I've tried changing the pin it's connected to, it's still dim. I've included my code below if it helps.

Thanks in advance.

int ledPin = 13;
int ledPin2 = 9;
int EP = 7;
int cal = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT); //set EP input for measurement
  Serial.begin(9600); //init serial 9600
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();
    if (c == '1') {
      cal = 100;
    }
    if (c == '2') {
      cal = 200;
    }
    if (c == '3') {
      cal = 300;
    }
    if (c == '4') {
      cal = 400;
    }
    if (c == '5') {
      cal = 500;
    }
    if (c == '6') {
      cal = 600;
    }
    if (c == '7') {
      cal = 700;
    }
    if (c == '8') {
      cal = 800;
    }
    if (c == '9') {
      cal = 900;
    }
    if (c == '0') {
      int randm = random(2, 6);
      int x = randm * 1000;
      digitalWrite(ledPin2, HIGH);
      delay(x);
      unsigned int tm = millis();
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, LOW);
      while (1) {
        long measurement = TP_init();
        char br = Serial.read();
        if (br == 'x') {
          break;
        }
        if (measurement > cal) {
          digitalWrite(ledPin, LOW);
          unsigned int out = millis() - tm;
          unsigned char i = out;
          Serial.print(out);
          break;
        }
      }
    }
  }
}

long TP_init() {
  delay(0);
  long measurement = pulseIn (EP, HIGH);
  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

You need to add this line for the other LED pin:

pinMode(ledPin2, OUTPUT);


Is it possible to reduce the size of this program to 1KB I want to use attiny13 in my project but this program is going over 1KB

void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay;
}
void loop()
{
  for (int i=0 ;i < 1 ;i++)
  {
    delay(1500);

    Serial.print("AT+CMGS=\"");
    Serial.print("+918269394684");
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("22.7010709,75.9372517");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
  }
}

There are several problems with your program as shown that make a good answer impossible.  After I list those problems, I'll then proceed to give an answer, partly good, partly bad.  The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays.  The bad part is that it sends at 115200 bps instead of 9600.  Depending on point of view, it may be good or may be bad that the code doesn't look for absence of '>' on Serial input; as I note in discussion of problems, the original code's unclear.

As promised, here are several problems with your program as shown, and how to fix them:

The statement delay; is a constant expression [address of the delay() function rather than a call to delay()] so take it out.
The statement for (int i=0 ;i < 1 ;i++) is a do-nothing so take it out.
The sequence while(Serial.read()!='>'); { is confusing – it compiles but isn't something a rational programmer would write – so take it out.  (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads '>' on Serial input.  Then the unnecessarily-blocked block of statements within the matched braces executes one time and loop() exits its current pass.  If the semicolon weren't there, the statements within the braces would execute repeatedly until a '>' appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the BasicSerial library from nerdralph's writing AVR assembler code with Arduino page, we get the following message for the program shown below.

  Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes.  Global variables use 68 bytes of dynamic memory.

#include <BasicSerial.h>
char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
#define send(item) while (*item) TxByte (*item++)
void setup() {
  //Serial.begin(9600);
  delay(2000);
  //Serial.write("AT+CMGF=1\n");
  send(text);
  //delay;
}
void loop() {
  char *msg = text;
  delay(1500);          // took out `for`
  //Serial.write("AT+CMGS=\"+918269394684\"");
  send(msg);
  //while(Serial.read()!='>'); {
  //Serial.write("22.7010709,75.9372517");
  send(msg);
  delay(500);
  //Serial.write("\033\r\n");
  send(msg);
  delay(5000);
  //}
}

Program Notes:

The string text contains all the text from your original Serial prints and writes.  With the text organized as a single string, the program only needs to set its character pointer msg once per loop, saving perhaps half a dozen bytes of code.
The commented-out Serial.write statements are equivalents of your various Serial.println, Serial.print, and Serial.write statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before delay(5000).  Just changing those printlns, prints and writes all to writes reduces code size  by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from.  But in my tests, substituting BasicSerial in place of Serial saves over a thousand bytes so is likely to be a requirement.
You probably can modify the code in BasicSerial.S for other data rates, or perhaps can substitute one or another of the small Serial replacements listed in ernstc's Serial communication with the Tiny's webpage, to get different data rates and/or receive as well as transmit.

Edit:  As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail.  RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default).  See the following revision of the program, which also corrects a problem (leaving msg pointed at a null byte) that would keep the former program from working.  Note, with these changes, we have:

  Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes.     Global variables use 6 bytes of dynamic memory.

#include <BasicSerial.h>
#include <avr/pgmspace.h>
const char text[] PROGMEM = "AT+CMGF=1\n\0"
  "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
char *front = (char*)text;
#define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

void setup() {
  delay(2000);
  send(front);  ++front;
}
void loop() {
  char *msg = front;
  delay(1500);
  send(msg);   ++msg;
  send(msg);   ++msg;
  delay(500);
  send(msg);
  delay(5000);
}


What sensor would detect the black stripe on an analog electricity meter? I have an analog electricity meter (AEM) and I would like to track my usage of electricity.
I've attempted to use the EE-SY310 photo sensor, but that's not sensitive enough it seems. I suspect the black stripe on the dial is too thin to be picked up. The other concern on using any photo sensor is its dependance on light (obviously) hence no reading would be picked up during the night.

Other: I've also found that AEMs work by using magnetic fields to move the dial. The magnetic field detector I used did not show much fluctuation when turning appliances on/off. The dial was pegged at the max. Therefore, I'm not so confident that a sensor to measure magnetic fields would work here, but I'm open to suggestions.

So, would anyone know what sensor would be good to detect the black stripe on AEMs?
Preferably to also work without light.

I know there are off-the-shelve products that do this already, but where's the fun in that?

A low cost option is the TCRT5000 infrared proximity sensor. While this is designed to sense objects coming close to the sensor, by reflection of the infrared light emitted by the integrated IR LED, it also does very well in detecting black versus reflective surfaces placed near it.

There are two parts to making this work:

Reduce the drive current for the IR LED of the TCRT5000 to the bare minimum which causes detection of the non-black portion of the electricity meter disc. While the datasheet specifies a forward current of up to 60 mA absolute maximum, a quick experiment I conducted shows appreciable detected signal at as little as 4 mA forward current, for a metallic target surface 2 mm away. Tune the forward current to work with the actual distance and reflectivity of your particular electricity meter wheel.
Place a black piece of card or plastic in front of the detector part of the TCRT5000, with a thin slit cut in it to align with the black strip on the electricity meter wheel. I am getting good results using a 1.2 mm plastic sheet with a 0.3 x 1.5 mm slit cut in it.
Note that the two hemispherical plastic parts of the TCRT5000 look more or less the same, so you will have to identify which one is the detector, and ensure that you do not obstruct the emitter by mistake. The side with the angled vertical edges (right side of image below) is the emitter and must not be obstructed.

With this arrangement, the collector current through detector will dip significantly each time the black stripe passes in front of the detector.


Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega? The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

  In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

  Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the TLC5940 but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or 74HC125 and a pull-low resistor.

Cheers!


Connect an Arduino directly to RGB LED strip I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB Strips. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

one cable on 12V
one cable on G
one cable or R
one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.


How to avoid that my arduino clicks eternally? I have accidentally implemented a program that imitates the click of the mouse.

The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.

Can I solve this problem?

Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer.  Load Blink.ino into the IDE and compile it.  Press the UPLOAD button in the IDE and move the mouse to somewhere "safe".  Release the RESET button.

Do those last three steps in rapid succession and you should be fine.


How to send keyboard signals to two separate computers (arduino due) The arduino due has 2 micro-usb ports that you can connect to two separate computers. I need to send different keyboard signals to each computer. How would I do this?

For one of them, use Keyboard as you normally would.

For the other, do whatever Can the 2nd MCU on the UNO R3 be used for keyboard emulation? tells you to do to reprogram the ATmega16U2 connected to the other USB connector.


USB control panel with endless turn knobs I understand that some arduinos are capable of presenting themselves as a USB HID device to a PC.

I would like to use one to build a custom input controller that lets me read maybe 8 or so turn knobs that can infinitely turn left and right.

I am new to Arduino, but have cross-compiled avr binaries before.

Which arduino would be a good choice for this? And any additional parts that would help?

The end product would look like a MIDI mix panel, but it shouldn’t talk MIDI, just USB HID (to a linux PC.)

Note: there is an expensive, and out of stock, device that is similar to what I have in mind called MIDI Fighter Twister, pictured below, to get an idea.

Options for the Arduino you have:

Get an Arduino supporting HID drivers (e.g. 32u4 based boards, Due /Zero/ Arduino Leonardo/ Micro or Pro Micro/ M0)
You use this library it supports UNO/MEGA/Leonardo/(Pro)Micro/ any 8u2/16u2/at90usb8/162/32u2/32u4 compatible boards and some more

Then you have to "just" code the communication between your programm and the HID driver -> pretty standard serial/usb stuff.
The parts (knobs) you seek could be rotary encoders, which have no fixed zero point, endless rotation and need 2 input pins per encoder (except GND or optional push function). The signals a rotary encoder produces (and what can be handled by libraries) are based on a 2-bit gray code available on 2 digital data signal lines.
So when choosing whatever Arduino make sure you have enough (usable) I/O ports for the number of encoders and possible additional parts (status led/s or similar, I2C LCD display)


Can any Arduino Due pin be used for PWM? Arduino Due has 54 pins. It says that it has 12 PWM pins. I know it uses a more powerful chip than other Arduinos.

Can the number of PWM be increased?

Can any of its pin be used for PWM?

According to the manual:

"The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs."

https://www.arduino.cc/en/Reference/AnalogWrite


Help: convert Arduino code to avr-gcc code I need to convert Arduino code to avr-gcc code. This is code:

#include <Servo.h>

Servo myservo;

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

void loop() {
  myservo.write(67);
}

I use Arduino Mega.

Try this:

#include <Servo.h>

extern "C" void init(void);

Servo myservo;

int main()
{
    init();
    myservo.attach(11);
    for (;;) {
        myservo.write(67);
    }
}

Note that this still needs the Arduino core library, as the Servo
library depends on it, which means all this is an exercise in futility.
If you are using the Arduino core, the simplest thing is to use it the
Arduino way. If you do not want to use Arduino core, then you will have
to partially re-implement the Servo library.


Arduino/ESP8266 to put PC to sleep and wake it up I have a Wemos D1 mini that's connected to a pc with usb, I want to be able to sleep the pc and wake it up programmatically.

Is there a way to do this? Like sending a simulated sleep keyboard button press?

Maybe I can send a wake up on lan command from the Wemos since they both are connected to the same router, but I'm still more interested in sending a sleep command.

I found this but it's old and it looks like they don't really have a way to do it.

The hardware interface would be the easiest like others were saying.
Here is a project someone else shared that does that.

https://www.hackster.io/zvonko-bockaj/wemos-esp8266-remote-pc-switch-062c7a

The wake-on-lan part is easy and here is some code for that.

https://github.com/koen-github/WakeOnLan-ESP8266

I'm also interested in sending some kind of RPC call to a system (linux/windows/mac) via wifi to initiate a shutdown.  If I find a solution I will post it here.

UPDATE: I found a Sleep-On-Lan project that should work.  You can use the same code above for the ESP8266 but just reverse the MAC Address of the system you want to shutdown.

https://github.com/SR-G/sleep-on-lan

You will need to run this as a service on the system you intend to put to sleep.  There is a windows and linux version.  They didn't mention mac but I bet it will compile and run on a mac too.  :)

I hope this helps.  I will probably use this myself in the future.


3v3 ESP one way communication with 5 V Arduino? Perhaps I'm not fully understanding a difference between logic level and the function of the TX and RX pins? I'm just wondering if an ESP can send, one-way, data to an Arduino. (I found that two-way communication would need a logic level converter.)
ESP32 Datasheet

https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf#page=42

Arduino datasheets do not appear to specify logic level tolerances. It appears from this Arduino Forum post, it would work.
Is it universally assumed that 3v3 will be in tolerance for logic high?

https://learn.sparkfun.com/tutorials/logic-levels/all

Yes, it will work, but only just. It's borderline.
The ESP32 gives out at most 3.3V as a HIGH signal. The Arduino accepts "above 0.6Vcc" as a HIGH signal. That means that it needs to see a voltage that is at least 60% of the voltage on the Vcc pin (5V pin) of the Arduino.
If the Arduino has exactly 5V then 60% of that is 3V. Since 3.3V is higher than 3V it sees it has a HIGH.
However if the Arduino is being powered by a slightly higher voltage than 5V (some USB ports can give out 5.2V and it's still in spec) and if the ESP32 is being powered slightly below 3.3V, then that 0.3v margin of error gets narrower and narrower. Eventually it disappears and HIGH can no longer be detected.
For example if the Arduino has 5.2V and the ESP32 has 3.1V then the Arduino expects at least 3.12V and the ESP32 gives out no more than 3.1V.
So in  most circumstances it does work, but there are factors that can stop it from working. Those factors can be mitigated by using logic level translation.


How to connect an Arduino to WIFI using an ESP8266 Hi I am trying to make Arduino Uno on local network with the help of ESP8266 wifi module.

I tried to search on internet, found mostly they are making ESP8266 as web server.http://circuits4you.com/2016/12/16/esp8266-web-server-html/

Can anyone help me how to add Arduino Uno on network with the help of ESP8266.

Sending the following commands to the ESP should get you started:

AT+RST                         # Reset
AT+CWMODE=1                    # Set to station-mode as a client
ATE0                           # turn off command echo
AT+CWLAP                       # optional: list access points
AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

(I made-up the comment syntax; don't try to send those.) The full
ESP8266 AT Instruction Set has the complete set of commands and a functional description of each one.

Update:

  ... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to
  TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).


Communicating with a 12V device? I'd like to connect a 12V access control device to the Arduino, but I lack the understanding.

How can the signals from and to the device be done when they have different voltages?

I am afraid that the 12V would brick the Arduino.

You could use an opto-coupler:

An opto-isolator (also called an optocoupler, photocoupler, or optical
isolator) is an electronic component that transfers electrical signals
between two isolated circuits by using light. Opto-isolators
prevent high voltages from affecting the system receiving the
signal. Commercially available opto-isolators withstand
input-to-output voltages up to 10 kV and voltage transients with
speeds up to 25 kV/μs.
A common type of opto-isolator consists of an LED and a
phototransistor in the same opaque package. Other types of
source-sensor combinations include LED-photodiode, LED-LASCR, and
lamp-photoresistor pairs. Usually opto-isolators transfer digital
(on-off) signals, but some techniques allow them to be used with
analog signals.

Here is an example schematic and packaging:

If you have a heavy load (although this does not seem to be your case) then they can also be used in conjunction with relays - here is an eight channel opto-coupler relay module board:


Tian stops working after some hours I'm having a very strange problem. I have a Tian that is programmed to send out sensor data to a server
every x seconds.
My program run well but after 14,15 hours of operation it stops working and I don't receive datas. The program is fast at the beginning, then after 2 to 3 hours before stopping, it becomes more and more slow with the message "timeout".

I think maybe a misuse of the Ciao library on my part could be at the root of the problem. Or maybe a modification at the program level could correct the problem. So if I can have some help about this..
(the problem doesn't come from the use of String, I have already tested use of array with cstrings and it doesn't work).

Here is the part of the program that I think is problematic (there is another CiaoReadWrite nearly similar to the first) :

void CiaoReadWrite1() { CiaoData data = Ciao.read("restserver");
if (!data.isEmpty())
{
  String id = data.get(0);
  String sender = data.get(1);
  String message = data.get(2);

  splitString(message,"=",LtT2,9);

  gen            =LtT2[0].toInt(); LtT2[0]="";
  belt           =LtT2[1].toInt(); LtT2[1]="";
  genReady       =LtT2[2].toInt(); LtT2[2]="";
  hvOnOff        =LtT2[3].toInt(); LtT2[3]="";
  beep           =LtT2[4].toInt(); LtT2[4]="";
  heart1         =LtT2[5].toInt(); LtT2[5]="";
  sendConf       =LtT2[6].toInt(); LtT2[6]="";
  heart2FB       =LtT2[7].toInt(); LtT2[7]="";

  beepFB         =beep;
  heart1FB       =heart1;
  sendConfFB     =sendConf;

  Ciao.writeResponse("restserver",id, String(baroAlti*100)+"="+baroHumi*10+"="+baroPres+"="+baroTemp*10+"="+beepFB+"="+heart1FB+"="+heart2+"="+sendConfFB+"="+
                                      secCust1+"="+secCust2+"="+secEmrgSW+"="+secloop+"="+secLoop1+"="+secLoop2+"="+gndSwGnd+"="+gndSwUGnd+"="+statusA1+"="+
                                      statusA2+"="+statusA3+"="+beltStat1+"="+beltStat2+"="+beltStat3+"="+beltStat4+"="+request+"=");
  request++;
}

}

You're using the String (upper-case 'S') functions, which allocate and de-allocate memory, a limited commodity, even with 64K. The standard heap management functions will tend to fragment the heap into pieces too small for further use. That can make new allocations slower because the heap has to be searched for a big-enough piece, and can eventually make it the heap grow toward the stack, until a collision (something gets overwritten) inevitable. We can't say for sure that this is your problem; we don't have enough information.

But try allocating one or a few buffers large enough for the worst case requirement, and use the C string functions instead (lower-case 's'), sprintf(), strcpy(), strcat(), etc. instead.


Arduino send commands fast I need cnc machine to run as smooth as possible.
It receives commands like this "M_XY 10.233 20.123".
If i send command by command there is a slight delay between commands and its noticeable.
I set serial timeout to 5 ms.
I tried to send n commands and store them on arduino, but arduino cant store much in ram. There is a huge delay while sending n commands.
I was thinking about converting letters (machine writes letters) to bezier and sending arc by arc or letter by letter in arcs. Can atmega328p interpolate bezier fast enough?
Would it be faster if i send numbers in bytes instead of strings?
That would be 4 bytes per float and merge with union on arduino.
Is there any better way of doing this i don't know of?
Edit:
This is how string commands are processed.
void addCommByte(const byte b){
  if(commID == MAX_COMM+1){
    commID = 0;
    Serial.println("TOO LONG COMMAND");
    Serial.flush();
    return;
  }

  if(b == '\n'){
    comm[commID] = '\n';
    commID = 0;

    processCommand();
  }
  else if(b == '\r')
  {
    commID = 0;
  }
  else
  {
    comm[commID++] = b;
  }
}

void loop() {
  Serial.flush();
  while(Serial.available() > 0) {
    addCommByte(Serial.read());
  }
}

Edit. Way better way.
C# side. Check for endianness in c#. Arduino is little endian.
        public void MOV_X(float mm)
            {
                SendCharAsByte("q"[0]);
                SendFloatAsBytes(mm);
            }
        public void SendFloatAsBytes(float f)
        {
            byte[] vOut = BitConverter.GetBytes(f);
            serialPort.Write(vOut, 0, 4);
        }

        public void SendShortAsBytes(short f)
        {
            byte[] vOut = BitConverter.GetBytes(f);
            serialPort.Write(vOut, 0, 2);
        }

        public void SendCharAsByte(char c)
        {
            byte[] aaa = new byte[1];
            aaa[0] = (byte)c;
            serialPort.Write(aaa, 0, 1);
        }

Arduino side.
void loop() {
  while(Serial.available() > 0) {
    processV2(Serial.read());
  }
}
// from processV2
if(byt == 'q'){   // mov x
    float mm = readFloat();
    if(X_DIR == 1) mm *= -1.0;

    stepperXY.moveXForMMSync(mm);
    Serial.println("p");
    return;
  }
// merge bytes
union u_tag {
   byte b[4];
   float fval;
} u;

float readFloat(){
  Serial.readBytes(u.b, 4);
  return u.fval;
}

There is no need to flush serial.

If you have an existing CNC, you may have to abide by its comm protocol.  Otherwise, if the Arduino is part of a CNC you are building, and it is supposed to accept commands from a host computer, the first thing to do is make sure your baud rate is set higher than the default.  I have found 115200 to be a good choice for stability.  Next, you should avoid sending TTY-type text strings, and send binary values instead. You'd send an initial byte or word to specify the command type, followed by the data.  In my open-source DaqPort sketch for high-speed data acquisition https://www.daqarta.com/dw_rraa.htm I use the high nybble of the command to specify the general type, and the low nybble to specify more detail like channel number.  The sketch uses a big loop with if(Serial.available() > 0) to read the first byte, and a switch/case to determine what to do.  The the specific command reads the proper number of bytes and does whatever.  This is way faster than having to parse text and convert to binary.


how do I power my motor shield without an arduino uno? I want to power my motor shield without my UNO. I have connected the +ve and -ve terminals resulting in lighting up of the LED.

Is there any way to control the motors in this arrangement from the Arduino?

Welcome!

I'm not sure I understand what you are asking because what you are trying to do doesn't make much sense.

The motors connected to the motor shield are controlled by the output pins of the Arduino that the motor shield is plugged in to.

You could run jumper leads from an separate Arduino into your unplugged motor shield, but that's just extending what you already have.  You really do need some form of controller, not necessary a microprocessor, otherwise how can you go forwards and backwards?

Is the problem you have put the Arduino into a plastic case and you can't plug the motor shield in any more?  If so get a set of long male to female connectors (they look like the Arduino connectors) and use them as extensions.

Is the problem you have a different format of board and can't plug it in? If so use the wires method to form the correct connections.

I hope that answers your question, if not please try and explain what I'm misunderstanding.


Can multiple xbees send data to one xbee I am new to xbees. I want to have multiple xbees (up to 400 xbees) send data constantly to one xbee (receiver).This is just simple data like lets say 0 or 1 . Is this possible? Are there any limitations?

Yes, you can send data from 400 XBees to a single xbee. I would like to clarify one thing. XBees are connecting to a network, not to a particular xbee. And the devices connected in a network can communicate each other.


RGBW LED strip: which components are required? I'm brand new to this community, and in electronics as well.

I'm a software developer and I want to start a new journey with a project in mind: I want to control a 5 meters addressable LED strip for my living-room.

I need all the components for this project... I already know eclipse and Java world, but I need help in choosing the components for the project:

which Arduino (starter package maybe?)
LED strip (smd 5050 on sw2812b, sk6812, APA104...) more than 60 LEDs/m
Power Supply for the project

Can you point me to the right direction, posts that can be useful to me, so I can start on good basis?

NeoPixels

The strips based on the WS2812 / SK6812 and similar chips, known by some as NeoPixels, are clever ways of implementing fully-addressable 24-bit colour LEDs.

One of the clever things is that they only require one data wire, plus power and Gnd, i.e.

+5V
Data
Gnd

The pixel information is sent by precisely timed sequences of 24 bits per pixel. The first pixel "peels off" these 24 bits (ie. 3 x red / green / blue) and then passes the rest on to the next pixel, and so on.

Libraries

Various people have written libraries to do this for you including:

Adafruit library
NeoPixels Revealed: How to (not need to) generate precisely timed signals
My own library which uses SPI

Power

Each pixel draws around 60 mA at maximum brightness (showing white) so you need to allow for a heavy-duty power supply. Particularly if you have 5m of 144 pixels/m then that is 720 pixels, which would require 43.2 amps!

According to Adafruit:

  To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps.

Even that means you need 14.4 amps for your 720 pixels!

So bear that in mind when sizing your power supply.

Addressing methods

The Adafruit library (as far as I can tell) holds the pixel information in RAM, and then "dumps" it to the NeoPixels in one operation. This lets you do fancy things in memory, and copy the results to the pixels. However that means you need enough RAM for all this. At 3 bytes per pixel (24 bits), if you have 720 pixels, that will be 2160 bytes, which is more RAM than the smaller processors (like the Uno) have.

Larger processors (like the Mega) have more RAM.

An alternative method, as explained here does not keep the data in RAM, but generates the colours "procedurally" on-the-fly. This is much less RAM-intensive, but perhaps less flexible. On that page he links to a YouTube video which shows a humble Arduino Duemilanove (similar to a Uno) driving over 1000 pixels!

Procedural generation however can do quite a lot, for example you can set the entire string to a single colour, change that rapidly, or make a rainbow effect by increasing (say) the red value for each successive pixel. You can also make "chaser" effects quite simply.

The library I wrote is also designed to allow you to use minimal RAM. You could conceivably add in your own storage scheme, perhaps only storing one byte per pixel, with less bits per colour (eg. 2 bits each for red, green, blue) and that would reduce RAM requirements by a third.

Cabling run

You could try sending the data over 2m. I warn you that the timing for a zero-bit is that it has to go HIGH and then LOW within about 400 ns, so you can't afford to have the data signal degrade too much.

When I had a similar string of coloured LEDs set up at Xmas time (not NeoPixels however) I had a long run of a 5V power supply (just using a pair of figure-8 wire), and situated the processor quite close to the pixels. This is probably the safest way of doing it.


SPI Wiring Confusion I am currently trying to learn about SPI and how it works on the Arduino. I want to wire a MAX7219 chip to it to drive an 8x8 LED matrix with. Normally, I would assume the wiring from Arduino to MAX7219 goes:

PIN 10 SS -> CS
PIN 11 MOSI -> DIN
PIN 13 SCK -> CLK

And indeed, this answer confirms my assumption.
However, after going through some other resources and guides I found some confusing and conflicting information about how the pins on the two devices should be connected.

For instance, the documentation that came with my Arduino kit has this schematic.

This tutorial I found has the same wiring.

Most surprisingly, this tutorial doesn't even use the SPI pins at all.

What perplexes me the most is the sentence

  The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

Is this true? If yes, then what is the point of the SPI pins at all? Why are the pins wired in so many different configurations?
I am really confused by this.

SPI is a communication protocol, you can take advantage of some hardware optimizations by using the pins where that hardware is available or you can do everything by hand using any pin you like, with the disadvantage of a bigger and slower firmware.
In certain situations, like in the presence of a shield or a library already using those pins, the SPI pins might be unavailable and you have to resort to a software solution (aka bitbang, as you manipulate bits to generate the proper signals), otherwise use of the hardware SPI pins is strongly advised.


Wrong documentation for Mega2560 SPI Pins? This page https://store.arduino.cc/usa/mega-2560-r3 contains the following image under the Documentation section.

It shows digital pins 10 to 13 with labels SS, MOSI, MISO, and SCK. However, this page says that those are at pins 50 to 53 https://www.arduino.cc/en/reference/SPI.

Which page is correct?

The image is incorrect, unfortunately.
The SPI pins are below:
PB0 - #SS
PB1 - SCK
PB2 - MOSI
PB3 - MISO


What am I doing wrong with my millis()? Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().

 // Pin 13 is the LED

 int led = 13;        // pin 13 on the board
 int ledOFF = 8;      //led off time delay
 int ledON = 5;            //led on time delay
 unsigned long Timer = 0;      // store time
 int runtime = 10000;      // run loop for 10s

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

   Serial.begin(9600);
   delay(1000);
 }

 void loop() {
   Timer = millis();
   int state = 0;
   while(millis() - Timer <= runtime){
     Serial.println(Timer);
     if(state==0){
       digitalWrite(led,LOW);
       state = 1;
       delay(ledOFF);
     }
     else{
       digitalWrite(led,HIGH);
       state = 0;
       delay(ledON);
     }
    }
   }

as @Andre said on comment, you give variable 'Timer' a new value each loop. One of the solution is putting Timer = millis(); on the void setup instead on void loop


How many LED displays can be hooked to one Arduino board? I am new to Arduino development. I need to connect multiple led displays(between 20 and 100), such as this one to an Arduino board. The led displays will be pretty far out from each other.

How can this be achieved? How can i uniquely identify the LCD displays? At this point i need some 101 orientation.

The led displays will be pretty far out from each other.

Those are I2C connected displays. I2C is not designed (though there are technologies to allow it) to operate over long distances. It's designed primarily for communication between chips within a circuit board.

  How can i uniquely identify the LCD displays?

Since you can't change the I2C address of the displays you would either need a separate I2C bus for each one or employ some form of I2C multiplexer.

All of this is getting too complicated. The more accepted way of doing this would be to have a small microcontroller directly connected to each display (one display per microcontroller) and then make the microcontrollers communicate with each other (or with a single master) over some suitable communication medium (some wireless system, or a serial bus like RS485 or CAN, for example).

You're then just rubber-stamping the units as many times as you want, and connecting them all together.


Stepper Motors Strange Behaviour I am working in a project in which I need to control at the same time three NEMA17 stepper motors. In order to do so, I am using three DRV8825 drivers working at 12V connected to an Arduino MEGA.
This Arduino is generating the pulses in velocity ramps so that we have an accelerated movement to reach the goal.
The schematic I am using for connecting the drivers is the one that the manufacturer recommends:

With a digital analyzer, I can see that my velocity ramp is being generated properly:

In this picture below you can see how steps (ST) are generated once the direction (DR) is set for each of the motors. The time waiting after the direction change is bigger than the necessary established by the manufacturer and also does the duration of the step pulses.
Following this, the motors are supposed to make an accelerated movement until reaching a certain position and then, decelerate and stop.
Although, I am facing the problem that, in some cases, one of the motors (not always the same one) makes a few steps in the opposite direction of the movement and, after that, it executes the expected movement. This leads to, even of making the three motors perform the same movement, one of them finishes differently.
I tried to change the drivers but the same happens. Also, as I said before, I have checked that the pulses are correctly generated.
I would like to know if anyone has faced a similar problem or knows any reason that could lead to this strange behavior.
Thanks.

So, apparently the motors I am using have a optimal work range that doesn't start at 0 but 200PPS. Though, even generating properly the velocity ramps, when using a low acceleration, my motors would be running for some steps outside this optimal range, causing strange movements at the beginning of the movement.
In order to solve it, these non-optimal low velocities are avoided while accelerating so that motors enter directly to the optimal work area.


Working or functionality Serial.begin(9600) In recent practice, I found out some new things.

Serial.begin(9600);

What is mean of this line of code?

Why here, we always write 9600?

And can we write manually number means instead of 9600 let's say 10000?

Serial.begin(9600);

What is mean of this line of code?

Serial.begin(9600) doesn't actually print anything.

If you want to print "Hello world!" to the serial monitor then you have to use this line of code. Rather it initializes the serial connection at 9600 bits per second.

It is used for kind of handshaking means both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

Why here, we always write 9600?

And 9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Ardunio to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Ardunio IDE's serial monitor) to the same speed in order to see the data being sent.

And can we write manually number means instead of 9600 let's say 10000?
No, we can't write. There is a specific baud rate available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.


How to drive N channel gate correctly from Adafruit Feather pinout? I am learning how to create a soft latch power switch, using an N channel mosfet.

Currently, I have this:

simulate this circuit – Schematic created using CircuitLab

The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).

However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.

If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on.  If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.

I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin.  The pinMode is OUTPUT.

FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF

Here's the test code I'm using.
It simply flashes a build in LED 10 times then does a power off.

int ledPIN = 17;
int controlPin = 11;
int lDelay = 150;

bool shouldBeUp = true;

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

void loop()
{
  if (shouldBeUp) {
    for (int i = 0; i < 10; i++)
    {
      digitalWrite(ledPIN, LOW); // on
      delay(lDelay);
      digitalWrite(ledPIN, HIGH); // off
      delay(lDelay / 2);
    }

    // Leave the LED low
    digitalWrite(ledPIN, LOW);
    digitalWrite(controlPin, LOW);
    shouldBeUp = false;
  }
}

Any help is appreciated! Thank you :)

Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.

You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

simulate this circuit – Schematic created using CircuitLab

To hold the power on you now set the GPIO LOW instead of HIGH.

If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.