smooth DC motor control with millis So the task is to control 12v DC motor.
With first button, you can add up motor speed by certain speed step.
With second button, you can slow down motors speed by certain speed step.
With third button you cant speed up motor to its max, but problem is there that i must be done smoothly. For example i press third button and in motor starts to spin faster and faster till it reaches max speed. But now when i press this button motor jumps to it max, and i don't know why. There is no smoothness.
I cant use delay, must be done by millis
[code]
int speed = 0;
int motor = 5,
    fasterbutton = 7, slowerrbutton = 4, tillmaxbutton = 2;
unsigned long previousMillis = 0;
const long interval = 100;
const long smoothinterval = 5000;
boolean faster, slower, tillend;
int begginingspeed;
const int step = 3;
const int maxspeed = 255;

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, OUTPUT);
  pinMode(7, INPUT_PULLUP);
  Serial.begin(9600);
}
void loop() {
  tillend = digitalRead(2);
  slower = digitalRead(4);
  faster = digitalRead(7);

  //button Nr 7 start DC motor and festens up
  if (faster == !HIGH && begginingspeed < maxspeed) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed += step;
      if (faster == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR ON" );
      }
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      previousMillis = currentMillis;
    }
  }

  //button Nr 4 slows down  DC motor
  else if (slower == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      begginingspeed -= step;
      analogWrite(motor, begginingspeed);
      Serial.print('\n');
      Serial.print("Speed = " );
      speed = begginingspeed * 100 / maxspeed;
      Serial.print(speed, DEC);
      if (slower == !HIGH && speed < 1 ) {
        Serial.print('\n');
        Serial.print("MOTOR OFF" );
      }
      previousMillis = currentMillis;
    }
  }

  //button Nr 2 for smooth fastens up DC motor till max
  if (tillend == !HIGH && begginingspeed > 0) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis <= interval) {
      for (begginingspeed = begginingspeed; begginingspeed <= 255; begginingspeed += step)
        analogWrite(motor, begginingspeed);
    }
    previousMillis = currentMillis;
  }

}
[/code]

I suggest using a different logic in your program. I would first divide up the different parts of the project:

A code part, which reads the 3 buttons and sets/increments/decrements a variable based on the button clicks, and
a code part, which takes a variable as set point and ramps the PWM (analogWrite()) output up or down, until the set point is reached. (So the setpoint is the target speed/PWM value)

This division between "input code" and "output code" is rather common, since it often makes your code better structured and makes it possible to easily add new inputs for one single output.

Let us first look at the second part (ramping the PWM signal up and down). We need a variable, that holds the current PWM value, and one, that holds the current set point (for both we are starting with zero, thus the motor stands still here:
int current_speed = 0;
int speed_setpoint = 0;

We also need a timestamp variable for using millis() to regularly setting the PWM output according to the set point and the corresponding interval (here as a define). Additionally we also define the increment, with which the PWM value should be incremented on each sample:
unsigned long motor_timestamp;
#define MOTOR_SAMPLE_INTERVAL  100
#define MOTOR_SAMPLE_INCREMENT 3

We are doing all this in the global scope. Now in the loop function we first check for millis() and the timestamp (which gives us a regular sample interval for the motor speed) and then check, if the current speed is higher or lower than the setpoint and change the current_speed accordingly. At the end we write the value of current_speed to the output:
if(millis() - motor_timestamp > MOTOR_SAMPLE_INTERVAL){
    if(current_speed < speed_setpoint){
        current_speed += MOTOR_SAMPLE_INCREMENT;
    } else if(current_speed > speed_setpoint){
        current_speed -= MOTOR_SAMPLE_INCREMENT;
    }
    analogWrite(motor, current_speed);
    motor_timestamp += MOTOR_SAMPLE_INTERVAL;
 }

So now we current_speed of the motor will follow the speed_setpoint, but will only increment or decrement with the speed you set with the MOTOR_SAMPLE_INTERVAL and the MOTOR_SAMPLE_INCREMENT. The new target speed is simply set by giving the variable speed_setpoint a new value. The above code will take care of reaching it.

Now lets look at the first part (reading the buttons for changing a variable). At your current code, you need to hold the button down for the value to change. From your text is guess, that you want a click behavior (1 step in speed for 1 button click, meaning button press and release). For that I suggest using the Bounce2 library, which will handle the buttons - especially the debouncing - for you:
#include <Bounce2.h>
Bounce bounce = Bounce();

void setup(){
    bounce.attach( BOUNCE_PIN, INPUT_PULLUP );
    // DEBOUNCE INTERVAL IN MILLISECONDS
    bounce.interval(5); // interval in ms
}

void loop(){
    bounce.update();
    if(bounce.fell()){
        // Handle the button click here
    }
}

Inside the if(bounce.fell()) statement, you would handle the action for the button click, in this case: updating the speed_setpoint variable. Define an increment value for the buttons and do the increment/decrement in the if statements. In global scope:
#define BUTTON_SPEED_INCREMENT 4

In the loop() function:
if(slower_bounce.fell()){
    speed_setpoint -= BUTTON_SPEED_INCREMENT;
}
if(faster_bounce.fell()){
    speed_setpoint += BUTTON_SPEED_INCREMENT;
}
if(tillend_bounce.fell()){
    speed_setpoint = maxspeed;
}

Now you need to put all this together. I will leave that to you. You can then tune the behavior to your liking by changing the defines.

Note the following points:

The motor will accelerate linear. That should be fitting for you.

The code will restart the PWM wave at every MOTOR_SAMPLE_INTERVAL. That is ok for a motor when the interval is significantly higher than the PWM interval. When you choose the interval too low (like single digit milliseconds), you need to put the analogWrite() call into the if statements with the increment of speed_setpoint. That will take 1 more statement, but will solve the problem.

If you choose the MOTOR_SAMPLE_INTERVAL too low, the speed change will get stuttery


How do I (easily) power a 5 V 3-pin fan? I have a 5 V 3-pin fan. I want to be able to:

power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.

If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.

Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?

If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.

You are correct in your assumption that you can not power a fan from an Arduino directly.

Use a transistor, for example 2N2222 or BC548, which is switched by the Arduino, using a single pin, in order to provide sufficient current to the fan.

Such as this simple circuit (note that the 12V supply would be 5V in your case):

Source: Driving a PC fan - transistor with or without an optocoupler?1

However, as chrisl has pointed out, you fan has three pins and not two. The above circuit will only work for a two pin fan. In your case, for the reasons stated in Chrisl's answer, one pin goes to 5 V supply, one to GND and then third goes directly to the Arduino - let's say pin 3. Then you can use the code below.

Assuming that the fan is connected to pin 3, then the code will look like this:

const int fan = 3;

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

void loop() {
  int fanSpeed = 255;
  analogWrite(fan, fanSpeed);
}

This will run the fan at full blast. However, you can thereafter modify your code to vary the value of fanSpeed.

Furthermore, by reading an analog input pin (let's assume that you have a potentiometer hanging off A0), using analogRead(), you can use the read value to modify the value of fanSpeed directly (by dividing the value returned from analogRead() by four2 and then sending to analogWrite(), like so:

  int potPin = A0;
  fanSpeed = analogRead(potPin)/4;
  analogWrite(fan, fanSpeed);

or even more succinctly, do away with fanSpeed completely and use:

  int potPin = A0;
  analogWrite(fan,analogRead(potPin)/4);

1 Note that the code in the link in incorrect as it attempts to write values greater than 255 using analogWrite(). As stated here, Arduino reference - analogWrite(), analogWrite() takes values of 0-255, whereas analogRead() returns values of 0-1023

2 See the loop() function in Arduino reference - analogWrite() for another example.


ESP8266 12e Arduino IDE outputs garbage values on serial monitor I recently started using the ESP8266 12E (Amazon link) and hooked the board up to the Arduino IDE.

When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.

The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?

Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

The baud rate you specify in your program and the baud rate in the serial monitor must match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.

For example:

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.


SD.begin() fails second time When I remove the SD card and try to open a file, I can detect the error properly.

But how do I detect that the card has been replaced after an error? My first thought was to call SD.begin() again but it appears that this function returns true exactly once and false thereafter.

Simplified example:

void setup() {
  SD.begin(pin); // called exactly once. Works.
}
void loop() {
  // stuff
}

But this does not:

void setup() {
  SD.begin(pin); // first time calling this function: works.
}
void loop() {
  delay(1000);
  SD.begin(pin); // always fails
}

I'd rather not reset the microcontroller just for this.

I know this question is relatively old but still, if you wnat to run  SD.begin(chipselect); again first call if(root.isOpen()) root.close(); I added this to the library. This way SD.begin(chipselect) will return true if a card is present and false when it's not.


Using the same variable between if-statements within loop() I wonder if there is a good way to use the same variable value between two different if-statements within the loop().

Within the Servomotor section of the code, I want to use the value from the first if-statement's RewardTime within the next if-statement's RewardTime. Thus far, I cannot find a way to do it.
(Since there is no communication between these variables right now, the RewardTime remains 0).

I'd appreciate a certain guidance in this matter.

#include <Servo.h> // Library required for the servomotor (Make sure to download if not in the library)
#include <Button.h> // Library required for the microswitch (Make sure to download if not in the lbrary)

// PARAMETERS
// COPY THESE VALUES IN PROCESSING CODE MANUALLY
// Explanation: To prevent possible Arduino-Processing overflow. Do not want too much information flow between Arduino and Processing.
const float Scale = 1 * 1000; // milliseconds
const float Base = 1 * 1000; // milliseconds

Servo Servo1;
int servoPin = 9; // Declare the Servo pin
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

unsigned long previousMillis = 0;
bool switching = false;
int State = LOW;

char BirdSings = 0;
//static float RewardTime = 0;

void setup() {
   Servo1.attach(servoPin);
   analogWrite(9, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // MICROSWITCH
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println(1);
   if(button.isReleased())
    Serial.println(0);

   // SERVOMOTOR
   // Get times when the feeder is covered (food present) and uncovered (food not present)
    unsigned long currentMillis = millis();
    while (Serial.available() > 0) {
    unsigned long currentMillis = millis();
   if (Serial.read() == '\n') { // When there is a song
     //Serial.println(2); // Food is uncovered
     previousMillis = currentMillis; // 0 becomes the current milli
     static float RewardTime = (Serial.parseFloat() * Scale) + Base; // CALCULATE THE RewardTime HERE
     Serial.println(RewardTime);
     if (State == LOW)
      State = HIGH;
     else
      State = LOW;
    }
   }

  if (State == HIGH && switching == false){
    Servo1.write(0); // 0 degree
    unsigned long secondCurrentMillis = millis();
    if (secondCurrentMillis - previousMillis > RewardTime) { // USE THE ABOVE RewardTime HERE
      switching = true;
      previousMillis = secondCurrentMillis;
      if (State == LOW)
        State = HIGH;
      else
        State = LOW;
    }
  }
  if(State == LOW && switching == true){
    Servo1.write(90); // 90 degrees
    switching = false;
    //Serial.println(3); // Food is covered
    }
}

Make the variable global, thus put it outside the loop function; also you don't need the static keyword anymore.

float RewardTime = 0;

Than inside your first if statement, remove the static float keywords:

RewardTime = (Serial.parseFloat() * Scale) + Base;

Some other tips:

normally local variables do not start with a capital (so rewardTime is like most coding conventions)
Always use brackets.

if (State == LOW)
  State = HIGH;
else
  State = LOW;

Change to:

  if (State == LOW)
  {
    State = HIGH;
  }
  else
  {
    State = LOW;
  }

However, to make it more simpler, use the ternary operator, you can change it to:

State = (State == LOW ? HIGH : LOW);

Which means: if some condition ? Do this : Else do this;


CC3000 Wifi: Enable Debug How do I enable debugging using Adafruit CC3000?

I am using the Adafruit_CC3000_Library.  I've followed the WebClient.ino example sketch.  I'm able to make 300 to 400 HTTP requests, but eventually the connection will hang.

I have looked at the CC3000 source and utilities and found that the Adafruit_CC3000_Library has a &Printer reference in a local variable called CC3KPrinter.  I can't figure out how to enable or activate CC3KPrinter, as it is in a code block contingent on CHECK_PRINTER.  I thought that #define-ing some variables in my sketch would help:

// None of these flags seem to enable debug within the CC3000 code.
#define _CC3000_DEBUG  1
#define DEBUG_MODE     1
#define ENABLE_CC3K_PRINTER 1

An example code snippet within the CC3000 library that I'm trying to enable is at line 916:

  CHECK_PRINTER {
    CC3KPrinter->println(F("Timed out waiting to connect"));
  }

To enable debugging, you need to

uncomment ENABLE_CC3K_PRINTER in Adafruit_CC3000.h
If you want to pass in some debug stream other than the default Serial, you should pass a pointer to the object (which should inherit from Print, such as SD or Client) as the last argument to the constructor in your sketch:

Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

In utility/debug.h, change the value of DEBUG_MODE to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:

#define _CC3000_DEBUG  1

Because most of utility/debug.h is wrapped in the usual:

#ifndef _CC3000_DEBUG
.
.
.
#endif

Your #define, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include utility/debug.h as needed.


How to wire a hall effect sensor to arduino? it's a UGN3503 hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.

as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.

what i want is just simply read the data from sensor and if the number is above or under defined value do something.

do i need a pull up resistor and/or capacitor?

what's the right and standard way to wire a UGN3503 to arduino?

The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.

If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.

A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).

The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.


Why is the Arduino IDE ignoring my replacement start up code? I am trying to replace the standard startup code to save flash space.

I've put the new startup.s in my core directory and added the -nostartfiles parameter to the linker reciepe in my platform.txt.

When I compile with the IDE, it does not include my start code at all.

When I use Atmel Studio or a makefile, the code assembles and is included just fine.

How can I get the Arduino IDE to use my new start up code?

The Arduino builder is case sensitive and will only see files that end in .S and not files that end in .s.

Renaming the new start up file to startup.S and then deleting the precomplied core archive fixed the problem.

Note that committing this change to git slightly complicated!


Modify SSID and Passwords in WiFi sktechs This is a question about modifying sketches other than through the IDE.

I'm using an Arduino Uno r3 + Arduino WiFi Shield (not the 101).  Up to now I've been using the IDE to manually change the ssids and passwords to connect to wireless networks.  As a next step, I'd like to create something that will let update the ssid and password from a source other than an IDE, preferably a batch or bash file.  Over the air updates are out of the question (way too advanced) so it is safe to assume that all updates will be done via the USB cable.  Based on my limited knowledge of what I think needs to happen, I need to solve the following high-level problems:

Get the computer to recognize that a gateway is plugged into a USB port
Prompt the user to enter the new ssid and network password
Write to the ssid and password fields
Compile the code and save it (equivalent compile/upload in the IDE)
Run the sketch to find and connect to the network

I'd like this to look like two blank fields and a "submit" button to the user.

My imaginary use case is that I'm installing a clone of my gateway/sensor network at a technically-illiterate grandparent's house.  I have no idea where to begin or even if such a thing is possible!Assuming that it is possible, how can I make it easy for them to configure the gateway for use on their home network without resorting to the IDE?

Yes, this is possible. However, you need to have some programming skills (Java, C, C++, anything really that can cope with serial comms) to write the computer-side program.

Forget 'automatic' running of a program without installing a service on the target computer to constantly monitor incoming serial comms. That said, there's nothing to stop you doing that but to me it's an unnecessary extra step. If the End User can handle connecting the Arduino to the computer without having a breakdown, then they can probably cope with launching the input program themselves.

Hence, write a program for the target computer that analyses COM ports for active connections. For each connection, listen for some kind of identification sequence. Perform a basic 'handshake' to verify that it's found the Arduino. Once it has, allow the User to enter the WiFi details, which are then passed on to the Arduino via serial. If you're feeling slightly adventurous (the necessary code is provided with the Arduino IDE as an Example, so it's no real challenge) you could have the Arduino scan for networks and offer the User a list to choose from.

On the Arduino, include within the sketch a method of opening serial comms with the target computer. This can be either:

Within loop(), at regular intervals, which becomes redundant after you've performed the setup correctly; or
A one-time affair within setup(). Each time the Arduino is powered on it attempts to establish comms with the computer, but times out after 30 seconds of 'silence', thus the User has to launch the program on the computer within a reasonable time.

Whichever approach you choose, the code in the sketch follows a similar essence - send a unique message to whatever is listening (if anything at all!) and wait for a specific response. If the computer is connected and the program is running, it should answer. Provided the answer received by the Arduino is expected (thus 'handshake' mentioned earlier), it should then wait for the SSID/pass to be entered by the User and sent by the computer. From there, connecting the Arduino to the network is a trivial process.


HMC5883L not working in continuous mode! I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.

I noticed that the values on the Arduino IDE's serial monitor are constant.

Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.

But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.

So, why is that and what to do?

#include <I2C.h>

#define HMC5883L_read   0x3D
#define HMC5883L_write  0x3C

#define Configuration_Register_A    0x00  //Read/Write
#define Configuration_Register_B    0x01  //Read/Write
#define Mode_Register               0x02  //Read/Write
#define Data_Output_X_MSB_Register  0x03  //Read
#define Data_Output_X_LSB_Register  0x04  //Read
#define Data_Output_Z_MSB_Register  0x05  //Read
#define Data_Output_Z_LSB_Register  0x06  //Read
#define Data_Output_Y_MSB_Register  0x07  //Read
#define Data_Output_Y_LSB_Register  0x08  //Read
#define Status_Register             0x09  //Read
#define Identification_Register_A   0x10  //Read
#define Identification_Register_B   0x11  //Read
#define Identification_Register_C   0x12  //Read
#define declination_angle 3.46

void HMC5883L_init (void);
int16_t data_read (int16_t *results);
uint8_t HMC5883L_read_reg (uint8_t reg);

int16_t results[3];
float m_scale = 1.0;

void setup() {
  // put your setup code here, to run once:
  I2C_init();
  Serial.begin(9600);
  HMC5883L_init();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  data_read(results);
  Serial.print("x-axis = ");
  Serial.println(results[0]);
  Serial.print("z-axis = ");
  Serial.println(results[1]);
  Serial.print("y-axis = ");
  Serial.println(results[2]);
  Serial.println();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
_delay_ms(500);
}

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;
  I2C_start(HMC5883L_write);
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_start(HMC5883L_read);

  msb = I2C_rx();
  lsb = I2C_rx();
  results[0] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[1] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[2] = msb << 8 | lsb;

  I2C_stop();

  return status_of_process;
}

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  Serial.println(reg_dat);
}

Regards,

The problem stems from this function:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

  To minimize the communication between the master and this device, the address pointer updated automatically without
  master intervention. This automatic address pointer update has two additional features. First when address 12 or higher
  is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to
  address 03.

So you are actually writing:

REG  CONTENT
0x00 0x07
0x01 Configuration_Register_B (0x01)
0x02 0x01
0x03 Mode_Register (0x02)
0x04 0x00

You need to either start a new transaction for each register you want to set a value in (explicit setting) or rely on the address pointer increment to move to the right register for you (implicit setting).

So either:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

Or, since the registers are in sequence in the address space:

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(0x01);
  I2C_tx(0x00);
  I2C_stop();
}

Oh, and don't forget to have an I2C_stop() after reading your register in:

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop(); // <----- MISSING
  Serial.println(reg_dat);
}


Is Arduino Mega Hackable Over The Air After reviewing similar topics I've decided to ask this question below in the Security Stackexchange forum about 11 days ago.
https://security.stackexchange.com/questions/235423/is-arduino-mega-hackable-over-the-air
No one gave an answer yet, perhaps I was wrong about the medium that's why I am also posting the question here.
I am collecting data (by reading input registers) from a machine by RS-485 protocol and Arduino Mega 2560 hardware.
I am also sending this data from Arduino Mega to a NodeMCU which is connected to the internet over WiFi.
I made 100% sure that no physical interference can be performed on the hardware I setup.
But since this machine, I collect data from is controllable (by writing holding registers) over RS-485 (I've tested it) I have to make sure that Arduino's software cannot be changed/re-programmed/flashed over the air by someone.
There is no other device than NodeMCU which is open to the Internet and can be the source of vulnerability. And the only physical connections between Arduino & NodeMCU ar TX3+RX3 pins and power+ground pins.
I do not really care if the data or WiFi password or cloud server credentials are stolen. The only thing I care about is that Arduino is not flashed over the air which can ultimately damage the machine I am taking data from. Do you think this setup is safe regarding the information I present to you?

the bootloader doens't listen on RX/TX3.
to start the bootloader reset is required
to communicate with the bootloader a serial programmer must have STK500 protocol or a telnet bridge for avrdude, which your NodeMCU sketch doesn't have

If your NodeMCU sketch has OTA, then the sketch could be updated to an avrdude telnet bridge. then reset would be needed to activate the bootloader. If your NodeMCU doesn't have a wire to Mega reset pin or you don't have a command in your Mega sketch to activate the reset, some serial overload of your Mega sketch could be a way.
But all this doesn't have an effect because the bootloader only listens at RX0


What is Clock pin and Data pin, Orientation in Grove LED bar I'm trying to use Grove LED Bar with Arduino

  Grove – LED Bar is comprised of a 10 segment LED gauge bar and an
  MY9221 LED controlling chip. It can be used as an indicator for
  remaining battery life, voltage, water level, music volume or other
  values that require a gradient display. There are 10 LED bars in the
  LED bar graph: one red, one yellow, one light green, and seven green
  bars. Demo code is available to get you up and running quickly. It
  lights up the LEDs sequentially from red to green, so the entire bar
  graph is lit up in the end.

In the github example there are Clock pin, Data pin and Orientation.

// Arduino Clock pin, Data pin, Orientation
// Grove_LED_Bar bar(7, 6, 0);

https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/LP%20examples/BasicControl/BasicControl.ino

But I have no idea what are they. Where can I find the documentation for them?

on the LED circuit board there are a few connections, notably DI and DCKI.

The DI pin is the data pint and DCKI is the clock pin.

According to the header orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.


Keyboard key press listener Is there a way to make a listener for a key press to begin a loop?

Example:  I press the Tab key on my keyboard and the programmed loop begins running.

Essentially creating a keyboard hotkey.

The answer is yes and no.

Only the Arduino and its IDE, no.

The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.


How can I concatenate multiple byte Arrays into one Array I have three byte arrays. I first change their values during runtime and after that I want to combine them into one bigger 4th array.

byte a1[] = { 0x01, 0x00, 0x01 };
byte a2[] = { 0x00, 0x11, 0x01 };
byte a3[] = { 0x11, 0x00, 0x01 };

byte c1[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I first tried this, but it did not compile.

c1 = a1 + a2 + a3;

I also tried strcat() and I did got a error.

You can concatenate with memcpy. You just need to set the pointer at the right place inside the c1 array.

memcpy(c1, a1, sizeof(a1));
memcpy(c1+sizeof(a1), a2, sizeof(a2));
memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));


Xbee shield to shield connection sends but not receives correctly Setup:
2XArduino Uno
2x XBees S1
2x Sparkfun xbee shields.

My first arduino reads in values from a photoresistor and sends the values to the second arduino.
I know for sure the arduino is sending  values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .

Can someone please tell me what i am doing wrong?
I am doing this to make sure i get the right values before i beef up the project.

Sender sketch

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <XBee.h>
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int photocellReading;     // the analog reading from the analog resistor divider
 SoftwareSerial XBee(2,3);
void setup(void) {

  Serial.begin(9600);
  XBee.begin(9600);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Wireless LightDimmer");

}
 void loop(void) {
  photocellReading = analogRead(photocellPin);
  lcd.setCursor(0, 1);
  lcd.print("Photocell= ");
  lcd.setCursor(11, 2);
  lcd.print(photocellReading);
  //Serial.println(photocellReading);
  lcd.setCursor(20, 0);
  lcd.print("Measured in lux");

  delay (500);
  lcd.setCursor(20, 3);
  lcd.print(" ");
 // Serial.print("Analog reading = ");
 // Serial.print(photocellReading);
   photocellReading = 1023 - photocellReading;
 unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
   Serial.println( LEDbrightness);
    XBee.print(LEDbrightness);

  delay(1000);
}

recieving sketch

#include <SoftwareSerial.h>
#include <XBee.h>

SoftwareSerial XBee(2,3);

void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 }
void loop(){
 while ( Serial.available() > 0) {
 unsigned int num =  Serial.read();
 Serial.println(num);
 delay(2000);
 }
}

The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.


Why does exit status 1 stray '\302' in program pop up around Serial.println ( "-> Second Service load");? /*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Wire.h>
#include "ds3231.h"
#include <Servo.h>
int potpin = 0; // Analog pin is used to connect the potentiometer
int val; // Variable to read the value from the analog pin
int pause = 800; // Delay in open feeders (feed amount)

Servo myservo;  // create servo object to control a servo

#define BUFF_MAX 256

// First Service
uint8_t wake_HOUR1 = 12;
uint8_t wake_MINUTE1 = 56;
uint8_t wake_SECOND1 = 0;

// Second Service
uint8_t wake_HOUR2 = 18;
uint8_t wake_MINUTE2 = 30;

// How often to update the information to the standard output (ms)
unsigned long prev = 5000, interval = 5000;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write (0); // Set the position to 0

  Serial.begin (9600);
  Wire.begin ();
  DS3231_init (DS3231_INTCN);
  DS3231_clear_a1f ();
  DS3231_clear_a2f ();
  set_alarm ();
}

void loop()
{
   char buff [BUFF_MAX];
  unsigned long now = millis ();
  struct ts t;

  // Output through time (5000ms) The time and alarm clocks ustanovlennnye
  if ((now - prev> interval) && (Serial.available () <= 0)) {
    DS3231_get (& t);

    // Display current time
    snprintf (buff, BUFF_MAX, ".% d% 02d% 02d% 02d:.% 02d:% 02d", t.year,
             t.mon, t.mday, t.hour, t.min, t.sec);
    Serial.println (buff);

    // Display a1 debug info
    DS3231_get_a1 (& buff [0], 59);
    Serial.println (buff);
    DS3231_get_a2 (& buff [0], 59);
    Serial.println (buff);

    if (DS3231_triggered_a1 ()) {
      // INT has been pulled low
      Serial.println ( "-> First Service load");

  myservo.write(10);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there
  myservo.write(170);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there

      // Clear a1 alarm flag and let INT go into hi-z
      DS3231_clear_a1f ();
    }
    if (DS3231_triggered_a2 ()) {
      // INT has been pulled low
      Serial.println ( "-> Second Service load");

  myservo.write(10);                  // sets the servo position according to the scaled value
  delay(1000);                           // waits for the servo to get there
  myservo.write(170);                  // sets the servo position according to the scaled value
  delay(1000);
}

As Gerben notes, the stackoverflow question error: stray '\302' in program is about this issue.  Basically, your file contains one or more characters not valid in the current character set.  The character is either non-printing or a multi-byte unicode character.

How did the character get there? Some of the ways mentioned in the stackoverflow question are pressing ctrl-space or shift-space.

How to find the character and get rid of it?  You can look at output from hex-dumping the file, which will identify all characters definitively.  Or by trial and error you can delete and retype spaces in the region of the error.


WiFi thermometers: save different location string as const across many devices I've built a very simple WiFi thermometer out of an Adafruit ESP8266 HUZZAH breakout board and a TMP36 temperature sensor. I have it reporting the temperature over wifi to my computer which will be storing the data in a database for monitoring purposes. I'd like to make multiple of these devices and place them around the house. My question: I currently have the location of the board as a const char* on the board itself. Doing this for multiple devices is just a bad idea and a nightmare to manage. Is there some way of setting a location variable on the board that will persist across shutdowns? Or am I coming at the problem from completely the wrong direction?

With a set of DIP switches or jumpers on some of the GPIO, you could encode a unique number for each one - 16 of them with 4 I/Os f/ex. The same code could run on all of them, sample the unique ID  report it along with the temperature. Let the PC-side map IDs to locations.


SyslogAppender for log4esp I'd like to "merge" two Arduino libraires, namely log4Esp on one side and Syslog on the other, hence creating a syslog appender for log4esp.

My problem is that log4esp's Appender prototype expects a method to return an instance of Print to which it'll write the message.

Syslog can't be used in this way.

==> Question : How to create a "Print buffer" / where can I find which class extends Print?

Class Print is a base class of Arduino streaming. Stream is a derived class and adds reading capability. Print has only one abstract method write to write one byte to output or buffer. It is easy to implement a derived custom class.

The classes derived from Stream are classes for hardware and software serial like HardwareSerial for Serial singletons and different software serial implementations. From Stream is derived class File of the SD and SPIFFS library, TwoWire class for Wire singleton object, etc.

Class Client is derived from class Stream and is a base class for Arduino standard TCP networking. Examples of derived classes are EthernetClient, WiFiClient. For UDP, class UDP is derived from Stream, of course with implementations like EthernetUDP, WiFiUDP.

You can see this in the source code in local source file folders or in GitHub repositories.


Can you tell me if this circuit will work? Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.

Thank you! :)

These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.

For the Uno it is D3, D5, D6, D9, D10 & D11.

Unfortunately there are only 6 PWM capable pins and you need 8.

You could consider bit banging the PWM for the 7th & 8th motor.

Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.

If you need to control each motor separately (without bit banging) you may have to upgrade to a Arduino Mega 2560. The Mega has 15 PWM channels.

An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob


ESP32 Pins won't fit in solderless breadboard I bought an Adafrut Huzzah32 ESP32 for an IoT project. When the ESP32 arrived, I attempted to fit it into my existing breadboard, but I immediately noticed that no matter how hard I pushed, the pins wouldn't fit into the solderless breadboard.

I tried to find others with the same problem with no luck, so I went on amazon and purchased another breadboard (an Elegoo 830 tie-points Breadboard). It arrived today and I'm having the exact same problem. I don't want to use a soderable breadboard at this stage of the project as I'm just starting, but I don't know what else to do at this point.

I've Googled images of other peoples' setups and there pins are snug down in the board. What am I doing wrong? I've included photos below:

As you can see, the power module on the end fits fine but the ESP32 won't go down into the board. At this point, I've tried two different boards (one of those small Arduino ones and this one) with no luck.

Any suggestions?

You can see that the pins aren't even close to being down in the board.

I understand. These breadboards are pretty difficult to work with. Not only fitting an ESP-32 or similar board is difficult, these breadboards are not broad enough to expose all the GPIOs on both the sides.
I had solved this problem in this video. Do have a look. It might be helpful
https://youtu.be/CQlbE1x2i2g


Arduino Zero to Arduino Zero SPI configuration I am in the planning stage of chaning two ATSAMD21 with a Zero or Nano 33 bootloade r in a SPI connection. The rational for this is that i am in need of 30 pin GPIO expansion and using 2 mcp23s17 takes a fair bit amount of space and also slightly bit more expensive. Since the ATSAMD21 has theoretical 37 GPIOs why not use that. having not owned a zero board yet, i would like to know if:

Is it easily doable, just connecting the appropriate pins?

If so, i have read in the Arduino SPI documentation that the zero doesnt have any Slave Select for Master and Slave, does this mean i can use whatever i want? And just code it to detect that pin

Does the built in SPI library capable of handling the slightly higher clock speed of the zero ?

A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)

Based on this, I think a second SAMD21 is not the best solution.

They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.

But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.

Two MCP23S17 (QFN packages) don't take that much space.

SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.

And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.

A MCP23S17 can drive and sink 25 mA on each pin.

A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).

On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.

If you need capacitive  touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.

Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.


Can increasing the size of the software RX buffer cause problem in Arduino Uno If I were to increase the of the buffer array from 64 to say 512 will this bring any long term problem in the Arduino Uno.

Changing from this:

#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

to this:

#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 512 // RX buffer size
#endif

This is the header file of the software serial.

The buffer is in the UNO's limited (2K) RAM; you'd be using 1/4 of it for the input buffer. If your app is small enough and simple enough (limited call depth, specifcally), there may still be enough RAM for your app to run successfully. If you have lots of globals (remember to include libraries when you're considering RAM use), allocate much memory from the heap (with new or malloc()) or have a complex call structure such that funcA() calls funcB() calls funcC() calls ... (etc) so that many functions' stack-frames remain allocated at once - at any point in your program - your program could suffer a stack-collision: the call-stack descends low enough that it can overwrite, or get over-written by, your heap or global data.

Why do you want so large an input buffer? Will data be coming in a high rate or in large bursts, while processing of the data will be infrequent or occur at irregular times? Given the limited RAM in the UNO, running complex programs on one can require something of a balancing act in how you use resources.

Update:

  i was performing some AT commands with software serial and buffer limitation generated junk value

Other reasons why SoftwareSerial might return bad data are:

Using too high a baud rate (9600 baud seems to be about the max);
Code that turns the interrupts off too often or for too long;
Other devices creating too many interupts (perhaps a built-in timer running at a high rate).

The replies to most devices' AT commands that I know of are short enough to not require a huge receive buffer. Asking for list of WiFi SSIDs from an ESP8266 could generate a large reply but most responses should not overflow a more modest buffer.


Arduino UNO WiFi "wifi shield not present" I currently use the Arduino UNO WiFi, but when I try to use the WifiChatServer example, I keep getting the same error: wifi shield not present.

What am I doing wrong?

That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C->UART converter chip.

You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

  If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE.
  Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.


How to send data to multiple slave at a time I have one master and three slave devices and i need to send data to all the slaves at a time.is that possible if so how to check which slave has recieved the data first

The I2C protocol implements the general call/broadcast address for this purpose. If you send data to the address 0 (zero), this is interpreted as general call by all slaves. All slaves, that can receive data, will respond by pulling the SDA line to low in the acknowledgement cycle (the timing is set up by the masters clock so all slaves will do it at the same time, thus no problem with garbled data). Note, that you cannot read from the general call address, since then all slaves might transmit at the same time. As the Atmega328Ps (the microcontroller on the Arduino Uno) datasheet states:

  Note that transmitting the general call address followed by a Read bit
  is meaningless, as this would cause contention if several slaves started transmitting different data.

I think the Wire library does not do any read operations on the general call address to prevent this, so this would not block up the I2C bus.

  how to check which slave has recieved the first

Not, because all slaves receive the data at the same time. The I2C bus is much like the IP protocol in this topic. A master/sender is sending out packages of data with the address of the intended target. But it is up to the slaves/receivers to decide, on which address they want to listen. So on every I2C transmission you are sending data over the bus, that could be read by all slaves. Only that in normal operation a slave will decide to only listen to the bus, when it sees it's own address (or the general call address).


How to setup Uno + xbee shield 1.1 + wee wifi chip? I am an absolute beginner with electronics and Arduino.
I have this hardware:

arduino uno
xbee shield 1.1
wee wifi chip

I've tried to make them work (to connect my Uno to the Internet) but I can't find the right tutorial.

Are there good resources I should look at, or do you know how set this up?

As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named Wifi Client.

In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.

Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield.  Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.


Attiny88 programming with Arduino I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88  because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.

Is there any library to program Attiny88 with Arduino 1.6.5?

Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.

https://github.com/SpenceKonde/ATTinyCore


Can I change font Color and/or Type for IDE 1.5.6r2? The program becomes harder to read (at least on my particular monitor) after upgrading.

Any way to change font Color to darker color and/or Type to thicker stroke (like B in this question editor) for IDE 1.5.6r2?

Yes.

Under the file menu select the preferences. From this you can find and than view/edit the preferences.txt file, which has the color settings.

Example preferences.txt


Arduino sketch taking forever to upload, followed by multiple issues I am using Arduino Uno board with Windows 10. From the tutorials on Arduino website, I am trying to upload the following code:

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

void loop() {
  // put your main code here, to run repeatedly:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

It had undergone a series of issues:

First,
avrdude: ser_open(): can't open device "\\.\com3"

I searched for his issue, and found that most common solution id to go to device manager and change the name of the port, then unplug and plug again the arduino board. I did that

Second,

C:\Program Files (x86)\Arduino\hardware\tools\axr\bin\avr-ar:
unable to rename 'core.a'; reason: file exists\\

I thiught it could be a memory problem. I used the reset button on the board, and repeated steps from the solution to the first problem. I tried to upload the code again.

But now, I am not getting any error message. But the problem is that it is taking forever to upload the code. I see Uploading... status since a long while. The green progress bar is also complete, but no uploading completed till now.

Any help to understand and solve this will be appreciated.

When the Arduino IDE says its uploading but never uploads, it is most likely a COM port issue. Try plugging the Arduino in a different port and make sure you change the port in the IDE. The problem seems to be you have changed the Arduino port, but not in the IDE. The Arduino IDE registers the previous port as open and tries to upload the program to that port. Go to Tools > Serial Port and it should list the ports(example):

COM 2
COM 3
Arduino Uno at COM 4
•COM 4

Every time you unplug and replug the Arduino you should check your ports and select the appropriate one ( It usually says Arduino *type* at COM *port number*

COM 2
COM 3
•Arduino Uno at COM 4
COM 5


Connecting 2 arduino on same ground I'm working project which consist of 2 arduino running a 2 different sketch, However, can i make these 2 ic to run on same power +ve and same ground?

Yes, you can. Just be sure, that you connect both Arduinos in parallel to the power source (both power inputs together to the power output of the source and both grounds together to the ground of the source), so that the current for the second Arduino won't flow through the first Arduino. Also use a power source, that is capable oft providing enough current for your needs.


What Minimum Value Can I Measure With ACS712 30A Current Sensor? I am making an Arduino multimeter for current measurement. I first thought about using a shunt but that fails to work since I need to measure current in the mA range.

That model has a sensitivity of 66mV/A which means for every 1A of current passing through it outputs 66mV.
The Arduino's ADC when running at 5V has a resolution of (5/1024) 4.88mV per LSB.
That means that 4.88/66 gives you 0.074 - or 74mA per LSB.
Since 1LSB is considered to be in the noise area of the signal you can expect the minimum usable value to be double that - 148mA
Which is pretty useless for measuring currents in the mA range.
You would get better results with the 5A variant, but still not great.


My push button code doesn't work properly I'm using an OLED display connected to a push button.  I am trying to get my display to show two different values independently  by using the push button to switch between them. Here is a snap of my code from the loop function:

    if (buttonState == HIGH) {
    x=x+1;
  }
  if (x == 1) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(T);
  display.print(" degree");
  display.display();
  display.print(x);

}
    else if (x == 2) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(perventage);
  display.print(" %");
  display.display();
  display.print(x);
}
    else  {
      x=1;
      }

  delay(10);
}

x is defined as 1 initially out side the loop.
What happens is that when the circuit is turned on, the screen displays the value of T then what should happen is when I push the button it switches to the second value which is percentage, and I push again to go back to T. My issue is that the Arduino doesn't response to the push button all of the time sometimes it takes 1 click and other times it takes 6 or 8 fast clicks to switch between them and it doesn't stick to a specific number of pushes to switch.
What would you suggest me to change to fix it.

Edit: here is pic of my wiring diagram

You are reading the raw button state without debouncing it, so you may be getting 2 (or 4, or ...) pulses so quickly - off the same button-push - that the display or your eye can't respond that quickly. Here is Nick Gammon's tutorial on switches and buttons, including debouncing.

Also make sure you use a pull-down resistor on the button input-pin. Floating inputs are noise and will give you a lot of false signals.


Can we write text file to SD card that can also be read in windows? I tried to use Arduino SD Library, I was able to run Datalogger and Dumpfile sample application to verify that the bits and bytes are written perfectly in the SD card.  When I tried to read from windows, everything is null. Is there an Arduino library that can write text file compatible to windows text format?

Notepad in Windows will show the raw data in a file - in all its hideous glory. However, there are things to make sure of:

Make sure that what you write to a file is ASCII characters. By that I mean do not simply write a byte or word value, convert it to a string first:

byte value;
...

value = Sensor.read(); // Return a value from 0-99
Card.write(value);

The above code will write a byte of 0 to 99 to the file - but you probably don't want that! The byte 32 is a space; 65 is the capital letter A; and 97 is the lower case letter a. Say what?

Every byte is represented by a different character in Notepad, so you need to convert the byte 97 into TWO bytes - first the byte (character) 9, and then the byte (character) 7. How do you do that?

One easy way is to use the following:

byte value;
char buffer[8]; // Define once for temporary use

...
value = Sensor.read();
sprintf(buffer, " %d", value); // Store value in buffer as chars - with a leading space
Card.write(buffer);

The above will write one (or more) characters into the file depending on the value you want to print. If your existing data was just a series of 0 bytes, your old code would have been nothing but NULLs. This will (at least) print 0 0 0 0 0 0 0 0 0 0


Switch MPU6050 to send SCL data through A4 and SDA through A5 I have this MPU6050, and like most of the other MPU6050s, it is set up for SCL to be attached to A4 and SDA to be attached to A5. I have this shield on my Arduino Uno, which is configured for Sainsmart's (the company who made the shield) MPU6050, so the special MPU6050 pins are set up V, G, A5, A4, and my current setup needs V, G, A4, A5. I am using the built-in Wire library, I2CDev library, and the MPU6050 library. So I am wondering whether there is something in these libraries that define which pins it looks for my MPU6050 on, and if so how do I change it.

The pin definition is in hardware. There is nothing you can do to change it. However you could try to reprogram it to use a software i2c library instead of the hardware wire library.


Connecting microSD reader and e-paper display to Nano at the same time? Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose
Thanks!

No. Even the e-Paper alone is not usable by an Arduino Nano.


How to find the peak value of analog signal? I have a question .. Please help me I don't know how Arduino can read the peak value of the sensor signal. The value I want is in the ADC value .. What I want is ... for 5 seconds there will be 1 average value from the highest peak value of the sensor, and the ADC value. I will use pin A0, but I don't know how to code the program that I want. Please help me What is the code?

See if I understand this correctly: For a given time period you want to find the peak.

void setup()
{
  unsigned long int cur_time = 0 ;
  unsigned long int time_elapsed = 0;
  int peaks[20]; // say you want to find 20 peaks , 1 peak for data arriving between 5 secs
  int time_period = 5000;
  int data = 0;
  int mx=0;
}

void loop()
{
   for(int i = 0 ; i<20;i++)
   {
      cur_time = millis();
      while(cur_time - time_elapsed <=time_period)
      {
             if(mx==0)
              { mx = analogRead(A0); }
              else:
               {  data = analogread(A0);
                  mx = max(data , mx);
               }
              cur_time = millis();
        }
         time_elapsed = cur_time;
         peaks[i] = mx;
         mx = 0;
        }
  }

Hope this helps!!


Does the position in which you mount an IMU matter? Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.

When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?

For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.

It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.

Bottom line is: if you can line them up, things get simpler.


ESP Web Server calling javascript function Is there a way to call javascript functions from ESP?
I don't want to call ajax requests every few seconds. I want to update my values only when they change.

Can it by done? Thanx.

If you want server-push, you can use Server Sent Events or a Websocket instead of polling with XMLHttpRequest.

So yes, it can be done, and I have implemented both using a Nano 33 IoT at one end and Javascript in a browser on the other. Some example code is here: https://github.com/ocrdu/arduino-webinterface-sse and here: https://github.com/ocrdu/arduino-webinterface-websocket.

I don't know if there are convenient libraries for the ESPs to do this, though.


How to split a string into substring Arduino I'm about identify myself stupid, howcome I couldn' t figure out how to split a string into substring using arduino, even after 10 days of searching. The number is fact... So, As Mr.Arduino.cc says: string.substring() is just can be used as conditional phrase with loops like if. and there is no method such strtok() like in C can help me with this. So guys, I' m bagging you for help, please!

if (ks > 255 * 60)
            {
                    vek.print("Bu yazı, ", 25, 0);
                    vek.printNumI(255*60, 25, 8);
                    vek.print("karakterd-", 25, 16);
                    vek.print("en uzun ol", 25, 24);
                    vek.print("dugundan", 25, 32);
                    vek.print("gosterlemz", 25, 40);
            }

for (byte i = 0; i <= ss ; i ++)
            {
                    for (byte j = 0; j <= 6; j++)
                    {
                            int ilk_kar = j * 10 + i * 60;
                            int son_kar = ilk_kar + 10;

                            String yaz=readString.strtok(ilk_kar,son_kar);

                            vek.print(yaz, 25, j);

                            if (analogRead(A5) == 1023)
                            {
                                    continue;
                            }
                            else
                            {
                                    break;
                            }
                    }
            }
    }
}

Error: sketch_aug22a.ino: In function ‘void loop()’:
sketch_aug22a.ino:83:56: error: ‘class String’ has no member named ‘strtok’

What am I supposed to do?

Thanks, already...

Import the string.h library by adding #include <string.h> on top of your sketch, in order to use the strtok() function.
Checkout the usage example of strtok() here: http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok


Changing the order of blinking LEDs with the push of a button I am new to Arduino and I have written code that makes 3 LEDs blink while the push button is off, so the lights are blinking from left to right (1,0,0)(0,1,0)(0,0,1) and then repeat from left to right.

Now I am trying to modify this code so that whenever the system receives a High from the switch it reverses the order, so it should start blinking from right to left and keep blinking that way until I press the push button and then return to left to right.

I hope my issue is clear. I only know how to use the if & else.

Here is my code:

int switchState;
int switchst = LOW;
int d=LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == HIGH) {
    d= ~d;
    if(d==LOW) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  }  else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
  }
}

The problem with this code is that it doesn't keep blinking if I release the push button.

This is the old code. It only goes from left to right and keeps repeating.

int switchState = 0;
int switchst = LOW;

void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(2,INPUT);
}

void loop() {
  switchState = digitalRead(2);
  if (switchState == switchst) {
    digitalWrite(3,~switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,~switchst);
    digitalWrite(5,switchst);
    delay(200);
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,~switchst);
    delay(200);
  } else {
    digitalWrite(3,switchst);
    digitalWrite(4,switchst);
    digitalWrite(5,switchst);
  }
}

The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.

An if statement will be used to change the order.

So the program will be something like (not tested):

global:

bool blinkToRight = true;

in Setup:

pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);

In Loop:

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(true, false, false);
   show(false, true, false);
   show(false, false, true);
}
else
{
   show(false, false, true);
   show(false, true, false);
   show(true, false, false);
}

void show(bool led1, bool led2, bool led3)
{
   digitalWrite(2, led1);
   digitalWrite(3, led2);
   digitalWrite(4, led3);
   delay(200);
}

checkReverse will check the input button and returns true if the mode should be reversed.

However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.

See example: Debounce example

Since only one led will be on, you can also use the following functions for Loop and show:

In Loop:

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(3);
   show(4);
   show(5);
}
else
{
   show(5);
   show(4);
   show(3);
}

Show:

void show(int ledOn)
{
   digitalWrite(ledOn == 3);
   digitalWrite(ledOn == 4);
   digitalWrite(ledOn == 5);
   delay(200);
}

And it's even better to use constants:

const int LED1   = 3
const int LED2   = 4
const int LED3   = 5
const int BUTTON = 2

Setup:

pinMode(LED1  , OUTPUT);
pinMode(LED2  , OUTPUT);
pinMode(LED3  , OUTPUT);
pinMode(BUTTON, INPUT);

Loop

// Check if loop is reversed
blinkToRight = checkReverse();

if (blinkToRight)
{
   show(LED1);
   show(LED2);
   show(LED3);
}
else
{
   show(LED3);
   show(LED2);
   show(LED1);
}

Show:

void show(int ledOn)
{
   digitalWrite(ledOn == LED1);
   digitalWrite(ledOn == LED2);
   digitalWrite(ledOn == LED3);
   delay(200);
}


PROGMEM Corrupted Array I am trying to store a large number of values into a couple of arrays using PROGMEM, but I am finding that a few of the values are read back corrupted. I am storing just 1s and 0s, but when I read these values back, I will sometimes get values greater than 1. I am using a MEGA 2560 to do this.

// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = -1;
  switch(arr) {
    case 0:
      j = pgm_read_byte_far(VALUES_1 + i);
      Serial.println(j);
      return j;
    case 1:
      j = pgm_read_byte_far(VALUES_2 + i);
      Serial.println(j);
      return j;
    case 2:
      j = pgm_read_byte_far(VALUES_3 + i);
      Serial.println(j);
      return j;
    case 3:
      j = pgm_read_byte_far(VALUES_4 + i);
      Serial.println(j);
      return j;
    case 4:
      j = pgm_read_byte_far(VALUES_5 + i);
      Serial.println(j);
      return j;
  }

  Serial.println("Unable to return next value");
  return -1;
}

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

What I have noticed is that when I use pgm_read_byte_far for case 0 I will get garbage values for right away, but using pgm_read_byte_near will cause these garbage values to occur sometime later. Any insight to this problem is appreciated.

Just a follow up in case someone else has the same problem. One solution is Nick's answer in his comment, which grabs the far addresses first in the setup, storing them in an array, and using them. I

// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

long VALUES[] = { 0, 0, 0, 0, 0 };

const long ARR_LEN = 32000;
long index = 0;

void setup() {
  Serial.begin(57600);
  while (!Serial) {}

  VALUES[0] = (long) pgm_get_far_address(VALUES_1);
  VALUES[1] = (long) pgm_get_far_address(VALUES_2);
  VALUES[2] = (long) pgm_get_far_address(VALUES_3);
  VALUES[3] = (long) pgm_get_far_address(VALUES_4);
  VALUES[4] = (long) pgm_get_far_address(VALUES_5);
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = pgm_read_byte_far(VALUES[arr] + i);
  Serial.println(j);

  return j;
}

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

This runs perfectly with all bytes correct. The better answer would be to convert the bytes into bits like everyone else was saying in order to save memory space.


Using Arduino GSM with WiFi I have a project that requires  data to be sent online from a moving bus. I am using ESP8266F modules to send the data.

I am wondering what Arduino modules to buy that will act as an access point with wifi and will connect to the internet through GSM.

In this configuration, the ESP8266 will connect to the access point and will upload the data online.

I want to connect a DF robot "SIM808 GPS/GPRS/GSM Shield For Arduino" to an Arduino Yun and use them as a wifi access point to connect to the internet through GSM connection.

The ESP8266 (5 of them) will connect to the Arduino Yun and will then send variables to the internet through the internet connection provided by the GSM.

ESP is a full stack WiFi module. If you are intended to collect some data from several ESPs you can configure one more as an access point and collect those data from other ESPs as stations. At access pint you can make a small web server as well. To send aggregated data through GSM then you can use a GSM module wire-connected to this ESP. To avoid RF interference while GSM sends data, you should use different power sources and shielded twisted pair for connection. It may happan, that you will need to place GSM module at some distance from ESP access point to avoid overload of the receiver. Even better to use external antennae outside the bus for GSM and shield it inside the bus to minimise the interference. I do not see how Arduino can help here.


ESP8266 SPIFFS file not found I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.

In the set up, I refer to the following function to read the file:

String readTemplatefile(){
  String retval ="";
  File fr = SPIFFS.open("/templatecfg.htm", "r");

  if(!SPIFFS.exists("/templatecfg.htm")){

    Serial.println("Template file not available ");
    }
    while (fr.available()){
        retval += char(fr.read());
      }

fr.close();
Serial.println("Template file = ");
Serial.println(retval);
return retval;
}

I always get 'Template file not found'. I have

SPIFFS.begin();

at the beginning of the setup function

My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.

Thanks in advance to any help.

SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.


Using a phone battery as a power source possible? Use
I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The goal is to have the most compact and long-lasting battery possible for my arduino projects.

Note
I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.

Question
I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.

Also:
Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (http://www.gammon.com.au/power); If utilizing his methods on different batteries are better than using a phone battery please let me know...)

If Possible...
Does it make sense for something like a:

LED suit (lasting 12 hours)
Portable gaming system (lasting 8 hours) - similar to: (https://www.adafruit.com/products/2510)
I Know this is for Raspberry Pi
BlueTooth Speaker (lasting 6 hours)

etc...

Sounds like a good solution.

Just note that most cellphones use Lithium batteries. Those are typically around 3.7 volt. They require some special way of charging, or they may explode or catch on fire. They also get damaged if discharged too much.

These batteries may have some protection circuitry inside them. This would be ideal in your case, as it protects against over-discharge, and accidental shorts.

An alternative would be the cells used in notebooks called 18650s. These are available with protection and without. The advantage is that you have a standard size. You can buy battery holders for them. That way you can easily exchange batteries. You can also combine cells to create higher voltages.

As for the runtime; you can make a rough calculation of it.


Using multiple RTC libraries in one program There are multiple RTC libraries available, can I load several RTC libraries into my code and then use the functions I like from each one?  Will there be some conflict if for example I include DS1307.h   and RTCLib.h and other RTCXXXX.h libraries as well?

can I load several RTC libraries into my code and then use the functions I like from each one?

It will depend on the libraries. Most likely they had some persistent variables, global to the routines, that help information exchange. If only some of the routines are used and others not, values in those variables may not be consistent.

  Will there be some conflict

That will depend on the way those libraries are implemented. No way of telling without seeing the code.

The point of doing this is a little bit suspect. It is not clear to me why you would want to have more than 1 RTC in an environment. If you are thinking about giving your program the option to function with multiple RTCs (but using one RTC at any given time), you can use either macro (at compile time) or wrap the RTCs in a logic layer (at run time).

For example, you can have a rtc_init() to reset different RTCs; and rtc_read() to return the time from the rtc. rtc_read() can be implemented based on which RTC is detected during initialization...


Can't get deep sleep to work on Wemos D1 ESP8266 I have a Wemos D1 (ver. 2015-08) and I am trying to get it to sleep. I've managed to get it generally up and running/got wifi to work etc, but the deep sleep function is beyond me.

I tried connecting RX<-D0 pin to RESET, also tried with a 10k resistor. Neither worked. I then tried D2 (listed as gpi016 on the back of the board) to RESET, this also didn't work. Any ideas? It seems like this would be an incredible chip if I could get it to sleep. The example sketch below uploads fine and contacts the serial monitor, up until the point it sleeps.

 /* Deep Sleep - Blink
 *
 * Blinks the onboard LED, sleeps for 10 seconds and repeats
 *
 * Connections:
 * D0 -- RST
 *
 * If you cant reprogram as the ESP is sleeping, disconnect D0 - RST and try again
 */

// sleep for this many seconds
const int sleepSeconds = 5;

void setup() {
  Serial.begin(9600);
  Serial.println("\n\nWake up");
  pinMode(BUILTIN_LED, OUTPUT);
  // Connect D0 to RST to wake up
  pinMode(D0, WAKEUP_PULLUP);
  // LED: LOW = on, HIGH = off
  Serial.println("Start blinking");
  for (int i = 0; i < 20; i++) {
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(100);
  }
  Serial.println("Stop blinking");
  Serial.printf("Sleep for %d seconds\n\n", sleepSeconds);
  // convert to microseconds
  ESP.deepSleep(sleepSeconds * 1000000);
  Serial.println("sleep finished");
}

void loop() {
}

I had to physically connect D0 to RST to wake up the wemos.


ESP8266 library: 2 requests received instead of 1 I have a strange issue with my sketch using WiFiEsp.h library from https://github.com/bportaluri/WiFiEsp

When i send 1 request to my ESP8266 from my browser as http://192.168.0.25
, it seems that my ESP8266 receives 2 requests and run 2 times. See the sketch here and Serial Termninal:

void loop()
{
  // listen for incoming clients
  WiFiEspClient client = server.available();
  if (client) {
    Serial.println("New client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println("Sending response");

          // send a standard http response header
          // use \r\n instead of many println statements to speedup data send
          client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
            "\r\n");
          client.print("<!DOCTYPE HTML>\r\n");
          client.print("<html>\r\n");
          client.print("Hello World!\r\n");
          client.print("</html>\r\n");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(10);

    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }
}

Serial temrinal:

[WiFiEsp] Initializing ESP module
[WiFiEsp] Initilization successful - 2.0.0
Attempting to connect to WPA SSID: Numericable-6010
[WiFiEsp] Connected to Numericable-6010
You're connected to the network
SSID: Numericable-6010
IP Address: 192.168.0.25

To see this page in action, open a browser to http://192.168.0.25

[WiFiEsp] Server started on port 80
[WiFiEsp] New client 0
New client
GET / HTTP/1.1
Host: 192.168.0.25
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://192.168.0.25/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

Sending response
[WiFiEsp] Disconnecting  0
Client disconnected
[WiFiEsp] New client 1
New client
GET /favicon.ico HTTP/1.1
Host: 192.168.0.25
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
Accept: image/webp,image/apng,image/*,*/*;q=0.8
Referer: http://192.168.0.25/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7

Sending response
[WiFiEsp] Disconnecting  1
Client disconnected

Please, could you explain why 2 clients connected ? How can i disconnect just after the first one ?

Browsers automaticaly request /favicon.ico for sites. Add this to  section of your HTML to eliminate the 'favicon' request:

<link rel="icon" href="data:;base64,iVBORw0KGgo=">

client.println("HTTP/1.1 200 OK\r\n" "Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("");
client.println("<link rel='icon' href='data:;base64,iVBORw0KGgo='>");
client.println("");
client.println("Hello World!");
client.println("");

based on this SO answer, instead of pointing to a server, the icon is encoded in the href parameter as base64 string


Bluetooth module is neither sending nor receiving data at baudrate(115200) Im sending data between my arduino and android via bluetooth, using a simple chat app called "Bluetooth Terminal" . the code work perfectly at baudrate(9600) but I need to increase the speed to that of (115200) but nothing gets transmitted, or at least visible, anymore.

here's my code

#include <SoftwareSerial.h>

const int TXD = 3;
const int RXD = 4;
SoftwareSerial mrBlue(TXD, RXD);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mrBlue.begin(9600);

}

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

  if (mrBlue.available() > 0) {

    String data = mrBlue.readString();
    Serial.println(data);

  }

  if (Serial.available() > 0) {

    String data = Serial.readString();
    mrBlue.println(data);
  }

  delay(20);
}

Software serial is really limited because it needs relatively precise timing, full attention of CPU and there can't be any interruptions from other sources.

You can see source code for better understanding how it works.

And if you need faster communication, you should get board with more hardware serials.


Serial.read(): Value changes to ASCII when I input from Serial Monitor I was having some problems on a project, so to test my Arduino, I wrote the following program to check things. When I start the serial monitor, the value of i is 1, but after I start sending numbers, they change into ASCII. Why?

int i = 1;
void setup(){
  Serial.begin(9600);
}
void loop(){
  Serial.println(i);
  if(Serial.available()){
    i = Serial.read();
  }
}

When you send the character 1, Serial.read() returns the integer 49.
 Serial.println(i) then sends the characters 4, 9, carriage return and a newline.

If you want to get back the same characters that you sent, change the type of i to char.


Are these lcd and motor-shields stackable? first of all, I'm kindly apologizing for asking such stupid questions, but as my electronic-knowledge is dramatically limited, you are my only hope to get my problem solved.

I'm pretty new to Arduino and my plans are to stack a lcd shield on a motor shield, which is stacked on the Arduino.

My setup would be the following:

Arduino MEGA2560
LCD-Shield http://www.sainsmart.com/arduino/arduino-shields/lcd-shields/sainsmart-1602-lcd-keypad-shield-for-arduino-duemilanove-uno-mega2560-mega1280.html
Motor-Shield http://www.sainsmart.com/arduino/arduino-shields/motor-shields/sainsmart-l293d-motor-drive-shield-for-arduino-duemilanove-mega-uno-r3-avr-atmel.html

My target is to enter specific values trough the LCD-shield (with its buttons) and to control a stepper-motor related to those.

Now to my question: Can I realize my project with the mentioned parts and are the two shields stackable (with head extentions on the motor-shield) without creating interferences?

Thank you very much for your time and answers in advance.

Best regards,

irie

No, it doesn't look like it.

The LCD board uses digital pins 4-10 and analog 0

The motor board uses digital pins 3-12 if all motors are used.

If you need to stack boards look for boards that use I2C since they can share a single data bus.


I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display //Numbers 0-9.
int numberArray[10][7] = {
  { 0, 0, 0, 0, 0, 0, 1 }, //0
  { 1, 0, 0, 1, 1, 1, 1 }, //1
  { 0, 0, 1, 0, 0, 1, 0 }, //2
  { 0, 0, 0, 0, 1, 1, 0 }, //3
  { 1, 0, 0, 1, 1, 0, 0 }, //4
  { 0, 1, 0, 0, 1, 0, 0 }, //5
  { 0, 1, 0, 0, 0, 0, 0 }, //6
  { 0, 0, 0, 1, 1, 1, 1 }, //7
  { 0, 0, 0, 0, 0, 0, 0 }, //8
  { 0, 0, 0, 0, 1, 0, 0 }, //9
};

//Turn off all segments (common anode --> high = off)
void reset() {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, 1);
  }
}

//turn on both segments (don't write anything to them)
void on(){
  digitalWrite(4,1);
  digitalWrite(5,1);
}

void setup() {
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  reset();
  on();
}
void loop() {
  for (int i=0;i<99;i++){
    twoDigitNumber(i);
  }
}

void twoDigitNumber(int number){
    digitalWrite(4,1);                   //turn on left display
    digitalWrite(5,0);                   //turn on right display
    digit(int(floor(number/10)));        //display the tens digit
    delay(10);
    digitalWrite(4,0);                   //turn off left display
    digitalWrite(5,1);                   //turn on right display
    digit(int(number-floor(number/10))); //display the ones digit
    delay(10);
}

//make the displays show a single digit number
void digit(int number) {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, numberArray[number][12 - i]);
  }
}

This is my first time doing anything at all with Arduino, and I'm also brand new to the language.

I have a bit of circuitry attached to the display. I'm using 2n5551 NPN transistors to act as a switch. Collectors connected to 5v, bases are connected to pin 4/5 with a 200 ohm resistor. Emitters are connected to the common anode of the displays. pin 4 is for the left display, pin 5 for the right display. These are to display different numbers in each display. Something's probably wrong with this but I'm having a hard time learning about transistors.

When I use the function twoDigitNumber(), it only displays the number on the left display, but I can see a very dim copy of that same number on the right display. int() is there because i thought floor() would make it into a double and cause issues, but that didn't fix it.

I know every segment works. When I use digit(), it shows the same digit on both displays (as expected).

Any help is appreciated.

Missing pinmode(4,OUTPUT) in your setup routine.

As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:

const int leftDisplay = 4;
const int rightDisplay = 5;
const int seg1 = 12;
const int seg2 = 11;
[...]

You can also use HIGH and LOW instead of 1 and 0 for the digitalwrite elements


Arduino Nano stuck on uploading I recently bought an Arduino Nano ( a clone actually), I installed the CH340G drivers for it and got it working perfectly fine... Played around with it for a while and then kept it aside...

Now after sometime I get time to play with it again, I was actually trying to power it with my 11.1V 2200mAh 8C LiPo battery. So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Now I move on to my computer to program it but the Arduino IDE is stuck at uploading. It was working fine before, when I hit upload, the RX LED glows VERY dimly and the board just stays like that. Only the power LED glows up, not even the LED on pin 13 glows up.
Uploading to a UNO works perfectly fine.

This is the error I get after a while-

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

Did I burn my board? Or is it just a bootloader issue?

So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Unfortunately Vin on an Arduino Nano does not have a reverse polarity protection diode such as the Arduino Uno PWRin

  Did I burn my board?

Very probable. For more details please see "10 Ways to Destroy an Arduino".

Cheers!


What do the numbers behind lcd (0x27) mean? I can't seem to figure out what the numbers after 0x27 mean. I understand that 0x27 stands for the I2C address and POSITIVE stands for the backlight, but what do the other number mean?

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

Assuming You're using the same LCD library I'm using, there is a longer form of the constructor that takes pin assignments for the different pins on the I2C module, as Majenko says.

I'm at work, so I don't have access to my code, but your constructor looks a whole lot like the one I use for my module, which has non-standard pin assignment. (I got my LCD modules from oddWires, and they came without documentation. I had to do quite a bit of detective work to figure out how to make them work.)

EDIT

I use the Newliquidcrystal_1.3.5 library in my project, to interface the above-mentioned oddWires I2C LCD display. That library has various constructors, one of which takes all the parameters you list. Those extra numbers indicate the pins that connect to the I2C module.

My oddWires LCDs need exactly the settings you list in the constructor. Your milage may vary.

The long form is defined in the library header with

LiquidCrystal_I2C(
    uint8_t lcd_Addr,
    uint8_t En,
    uint8_t Rw,
    uint8_t Rs,

    uint8_t d4,
    uint8_t d5,
    uint8_t d6,
    uint8_t d7,
    uint8_t backlighPin,
    t_backlighPol pol
);

From the naming of the parameters you can deduce most of them:

En is an enable line
Rw is a read/write line?
Rs is ?
d4-47 are the data pins
backlightPin is the pin that turns backlight on and off
pol indicates the backlight polarity (POSITIVE probably means pull the line high to enable the backlight.


Coin Acceptor CH-925 Pulse I got a problem where pulse voltage from acceptor is about 20mV. How can I solve my problem? and I can't detect the pulse using arduino uno.
please any one can help ?

From this Amazon review:

  There are 'live' (12V), 'ground' and 'signal' wires coming out of the
  back. Live and ground are pretty self-explanatory, and need to be
  connected to a 12V supply - I bought a simple 1A DC one. The final
  wire says 'signal', and needs to be connected to your circuit as input
  into a GPIO pin in the case of a raspberry pi. It produces a pulsing
  5V signal (Why not tell us it will be 5V somewhere in the
  documentation? Luckily I have a multimeter) as a way of encoding which
  type of coin it has encountered. However, raspberry pi's only want
  3.3V signals as inputs, so you'll be wanting to make a voltage divider (With a couple of resistors - I used 33k and 18k) to safely bring that
  5V pulse down to 3.3V. (http://en.wikipedia.org/wiki/Voltage_divider)
  You'll also want to connect the ground from the device to a ground on
  your Raspberry Pi, or the signal won't work. I did this by splicing
  the ground cable from the power supply so that it has 2 ends - 1 for
  the power supply to the unit, and one for the unit to the Raspberry Pi
  Circuit.

It seems that a 5v pulse is the expected output. How are you measuring the output? You'll need a 'scope rather than a multimeter measuring voltage...

Anyway, I would not try to 'amplify' the signal, I would look to check the connections are correct and if that's not the issue, I would return the unit as defective.


Arduino Nano with CH340 reboots on OS X El Capitan I installed OS X El Capitan beta on my Macbook. Now my Nano-sized Chinese Arduino operating on CH340 chip reboots the laptop when USB is unplugged. While plugged, it works fine, I can upload sketches and send/receive data via Serial.

I've tried reinstalling the CH340 driver and running the following command as per this solution and it didn't help:

sudo nvram boot-args="kext-dev-mode=1 rootless=0"

I appreciate any ideas...

There is a new signed driver for OS-X El Capitan and Yosemite. This is all you want.

http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html


What is 1.8 to 5.5 VDC? I'd like to buy a standalone capacitive touch sensor to create interactive art.  It says it is powered by 1.8 to 5.5 VDC.  I am new to arduinos - what type of battery can I buy to power this sensor?  I'm hoping it's simple, not complicated. Thanks!

VDC is an abbreviation for volts DC. DC means Direct Current you can read more a detailed explanation about it here. Basically what powered by 1.8 to 5.5 VDC means is that the DC voltage on the input of your sensor can vary from 1.8 volts up to 5.5 volts. So you can use either 3 AAA batteries in series since the sum of their voltage will be: 1.5V * 3 = 4.5V what is in the range of recommended voltages for your sensor. Also, you can use a Li-ion battery in order to power your sensor since the voltage of this type of battery is 3.7V it is also in the range of recommended voltages for your sensor. However you would need an additional charge/discharge module in order to recharge and keep the battery in a good condition. You can read more about it on the web.