text:
How to connect this motor driver board to Arduino to drive bidirectional motor?
I am familiar with using PWM on Arduino and have done so with simple 3-pin interfaces: e.g. PWM, DIR (direction) and GND pins. Choose a direction with DIR, set speed with PWM in software (0 - 255), simple stuff.
But this board I'm buying seems different:
http://www.ebay.com/itm/DC-43A-Double-BTS7960B-Stepper-Motor-Driver-H-Bridge-PWM-for-Arduino-Smart-Car-/141485439094
There seems to be 6 control pins:
R_IS, R_EN, RPWM, L_IS, L_EN, LPWM
But from what I understand this board would only be used for controlling one motor bidirectionally, so why is there a distinction between left and right?
So how would I go about using this motor driver board in a similar way to my PWM, DIR, GND boards that I've used before to control the motor direction and speed?
Thanks!


text:
AT+CIPSEND command closed the connection automatically

I don't know why CIPSEND command closed the connection after sending done without CIPCLOSE command. Is it normal?
If I want to keep the connection, what should I do in this case?

Perhaps it is an appropriate result of the "Connection: close" header?

I has changed to "keep-alive". It's still the same result. :(
I'm using Ajax jquery to take the data from Adruino. May Ajax has closed the connection automatically after receiving done? Im newbie in ajax.

I don't think anyone is required to honor a keep alive header sent by the other party, it is more of a suggestion.  But it may not be your issue either.  Maybe you should try something else against the server, or the ESP8266 against something else.

source: Stack Exchange

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

sort: votes


text:
Serial - Send data to Arduino while Arduino sending data
Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. Serial.available() returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?
PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.
Example code:
void loop(){

  if(Serial.available())
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

Please edit your question and post your code. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

@Nick Gammon, done.

That's not all your code is it? What baud rate are you using? In any case, since you are sending "hello" every time around loop the output buffer will be filled with hello before you get a chance to insert goodbye. Your "delay" solution probably gives the output buffer time to empty.

@Nick Gammon 9600.

And I lid a led when receive message. I forget to write it. Ill add full code when Im open PC. I dont have full code by now.

Following up on what Nick Gammon says, don't try to use the serial output to debug serial.  Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.
The following is how I've been reading a line at a time using non-blocking operations:
const int SERIAL_BUFFER_LENGTH = 100;

// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count;         // index into serial buffer

void setup() {
  Serial.begin(9600);  // or 115200 if your host supports it
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  g_char_count = 0;
}

void loop() {
  while(Serial.available() > 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    char c = Serial.read();   // won't block because Serial.available() > 0
    if (c == '\n') {
      g_serial_buffer[g_char_count] = '\0';  // null terminate
      process_buffer(g_serial_buffer);
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print(".");
}

// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}

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


text:
Do I really need Ramps 1.4 for laser engraver
I'm making 2-axis laser engraver like system. Arduino waits command from pc, on receive moves laser to next coordinate and send current coordinate to pc.
I have 3 step motors and I'm controlling them with Arduino Uno which is connected to A4988 drivers which is on breadboard. But almost all samples using Ramps. Do I miss something?

Ramps 1.4 is one of the proof of concept standards for 3D printer systems. It is a motherboard mostly runs Marlin firmware on it. I advice to to take a look at the firmware if you didn't yet. It is also supporting many motherboards, hardware.
When you open the configuration.h file in the firmware and search for this definition #define MOTHERBOARD you will be seeing many options available.
After all, the firmware is the key factor. It contains many engineering solutions in it. So, you shouldn't re-invent the wheel.
All you have to do is to adapt it with some tweaks as per your design specifications.
But, I would worry more about your motherboard (Arduino Uno)
if your design is relatively simple, using less memory and IO pins, it may be just fine. I would consider Mega 2560 instead If I were you.
Good luck with your project.


text:
Why does keyboard.h add 136 to each key?
I want to create a custom keyboard mapping in the official arduino keyboard library
Why do the key definitions add 136 to each number?
See Keyboard_es_ES.h on github
#define KEY_MASCULINE_ORDINAL    (136+0x35)
#define KEY_INVERTED_EXCLAMATION (136+0x2e)
#define KEY_GRAVE                (136+0x2f)
#define KEY_N_TILDE              (136+0x33)
#define KEY_ACUTE                (136+0x34)
#define KEY_C_CEDILLA            (136+0x31)

Looking at the ascii table, I see nothing special about value 136

It could be argued that this is an implementation detail of the library,
that does not need to be documented. ;-) Anyway, here is the reason...
The keyboard library uses a custom encoding scheme for representing
both characters and keys. The public methods press(), release(),
write(), print() and println() interpret the user-provided data
according to this scheme. With this encoding, the interpretation of a
byte depends on which of these three ranges it belongs to:

Bytes in the range [0, 127] are understood to be ASCII
characters. This is what enables you to write things like
Keyboard.println("Hello!");. The library uses a keyboard layout
array to map those characters to key scan codes¹, possibly modified by
Shift or AltGr. You provide a pointer to this array as an argument to
begin().

Bytes in the range [128, 135] are interpreted as modifier keys,
such as KEY_LEFT_CTRL, KEY_RIGHT_SHIFT, etc. Note that these keys
do not have proper scan codes, as their state is transmitted to the
host as a bit map (one byte for the eight keys) rather than as codes
added to a list.

Bytes in the range [136, 255] are interpreted as raw scan codes
in the range [0, 119], shifted by 136. This is what lets you
actuate arbitrary keys such as KEY_PRINT_SCREEN or KEY_LEFT_ARROW.
All scan codes of a standard full-size PC keyboard (ANSI 104 or
ISO 105) lie in the range [4, 101]: you can access all of
them, and even some more like KEY_F24.

Regarding the file Keyboard_es_ES.h: the codes in there are for keys
that match ASCII characters in the US layout but not in the Spanish
layout. The purpose is to ensure that every key of a ISO 105
keyboard can be actuated using either an ASCII character (like
Keyboard.press('a');) or a KEY_* macro.
¹ The USB standard calls them “usage codes”, but the old term “scan
codes” seems more prevalent.

Just an idea for self-documenting source, but I'm quite sure you are aware of this. ;-) You could use symbolic constants instead of magic numbers.

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


text:
Serializing data created by ATTiny85 for use on PC
Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to communicate with it from a PC as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).
The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.
Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

Is there any reason why V-USB isn't an option?

Haven't looked into V-USB yet. If it fits, I'm fine with that.

@IgnacioVazquez-Abrams So is this what we're talking about? http://codeandlife.com/2012/02/22/v-usb-with-attiny45-attiny85-without-a-crystal/

That article is badly out of date, but yes.

It might seem a little old fashioned, but a software implementation of an RS-232 type link could work for you. It might be easier than V-USB and require less resources on the AVR. I think that's the way I would go.  Regards,

The problem with using RS-232 with the ATtiny85 is that the '85 doesn't have a hardware UART. Its USI can be used to emulate one, but only in half duplex.

Sorry, I'm not up on my baud rates and hardware but what would that be equivalent of in units of bits per second? How fast could I shove 16 bytes to the ATTiny85 and back?

I think half duplex would work in this application.  A 16 char string comes in, gets processed, then a 16 byte string goes out.  Remember the V-USB has to send data, RS-232 can do it at the same rate, it seems to me.  Looking around the 'net it seems that LadyAda coded a interrupt driven software serial port which is now included in the base code for Arduino.  Here is a bit of a write-up:  http://arduiniana.org/libraries/newsoftserial/

Or you could use this.

So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with V-USB:

V-USB is a software-only implementation of a low-speed USB device for
  Atmel’s AVR® microcontrollers, making it possible to build USB
  hardware with almost any AVR® microcontroller, not requiring any
  additional chip.

Requirements: AVR microcontroller with at least 2 kB of Flash memory, 128 bytes RAM and a clock rate of at least 12 MHz.
Taken from ATTiny85's Datasheet:

8K Bytes of In-System Programmable Program Memory Flash
512 Bytes In-System Programmable EEPROM (enough for third-two 16-byte keys)
512 Bytes Internal SRAM

Looking forward to trying it out :)

Keep us updated on how it works out, please. Regards,

Haven't had a chance to implement this yet, but I might also look at your RS-232 recommendation. Ah, reminds me of my very first electronics project: the $4.00 serial link for my Ti-83+.

need to come up with a way to communicate with it from a PC

would be difficult to make an uart out of usi?

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

Yet another alternative is to use the Display Data Channel (DDC) on the PC. This is 5V and I2C. Unfortunately not all PC video boards support I2C. Please see the reference for further details.
I2C is supported on ATtiny by the USI module.
Cheers!


text:
Regarding use of software serial two times
Can we configure two digital pins as serial pins using software serial library?

Kind of, yes - however you can't use them both at once. SoftwareSerial is blocking. That is, while one port is receiving or sending data the other port will be completely locked out so won't be able to receive anything. So it kind of breaks it in a nasty way.
Personally I never advocate the use of software serial unless there is absolutely no choice whatsoever, and that is something I have never found.
If you need more than one UART then pick a chip with more than one UART.


text:
Ultrasonic Range Sensor won't print distance in Serial Monitor
I'm using the red Ultrasonic Range Sensor with
Sig -> Digital Pin 4
VCC -> 5V
GND -> GND
The code uploads fine and i can hear the sensor clicking away, but for some reason it won't print the distance into the Serial Monitor.
//Settings
int echoPin= 4;
int trigPin= 4;
unsigned long pulsetime = 0;
unsigned distance = 0;
unsigned OldDistance = 0;

void setup (){
  pinMode (echoPin, INPUT);
  pinMode (trigPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){

  //Work out the distance
  digitalWrite(trigPin, LOW);
  delayMicroseconds(100);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  pulsetime = pulseIn(echoPin, HIGH);
  distance = pulsetime / 58;
  delay(10);

  //Send value if it's changed
  if (OldDistance != distance) {

  Serial.print(distance);

  OldDistance = distance;
  }

  delay(50);  // Wait .1 Seconds
}

What kind of sensor?

Is it this one? http://www.rhydolabz.com/wiki/?p=895

Yup, that was the one.

You have to manually switch from OUTPUT (for sending the trigger pulse) and INPUT (for reading the distance) mode on the shared IO pin.
//Work out the distance
pinMode(trigPin, OUTPUT);    // << ADD THIS
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);     // << ADD THIS
pulsetime = pulseIn(echoPin, HIGH);
distance = pulsetime / 58;
delay(10);

To save some confusion you might like to change your code to just use sigPin instead of a pair of pins that are both the same pin.  That way you would avoid confusing bits like:
pinMode (echoPin, INPUT);
pinMode (trigPin, OUTPUT);

Which of course is the equivalent to:
pinMode (4, INPUT);
pinMode (4, OUTPUT);

Brilliant! Problem solved and i took your advice to just use a trigpin instead of trig and echo. Thanks!

Two suggestions:
In setup() after you open the serial port, execute something like Serial.println("Sensor Test Program");, and in loop, print the distance value with something like Serial.print("dist: "); Serial.println(distance);
That will tell you two things:

whether your port is open and working at all; and
whether control reached your output statement (in loop) and that it tried to print something.

In this case, it seems unlikely that control didn't reach Serial.print(distance); but more information, at least in the early stages, helps when things don't work as you'd expected them to.
You should have seen some output from your output statement, even if it was wrong. No output suggests:

control didn't get there (perhaps due to a program crash, especially if this is a fragment of a large program);
the terminal program and the Arduino's baud rates don't match;
the terminal program was opened to the wrong port;
the terminal program wasn't opened at all;
the calculation (or operation of the device, perhaps in the manner @majenko suggested) failed such that the distance calculation always yielded zero, and the 'if' statement was therefore never satisfied (my guess), i.e., back to my first point, control didn't get there.


text:
Arduino Yun Python ImportError: No Module named mime.multipart
So, I have an Arduino Yun, and I'm trying to send an email with python. I have this code that I got from https://github.com/amicojeko/YouCantTouchThis

But when I try to call the file with $python sendemail.py test.png, it returns me an error:

ImportError: No module named mime.multipart

I already tried to change to lowercase the imports, but it keeps showing the same error. The python version in the Arduino is 2.7. I've read something about module reorganization but even with the changes the error keep showing. Here is the code:

# coding=utf-8
# Copyright (C) 2014  Stefano Guglielmetti

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

#From address, to address, subject and message body
from_address    = 'FROM_ADDRESS@EMAIL.COM'
to_address      = ['YOUR_ADDRESS@EMAIL.COM']
email_subject   = 'Alert!!! Zombies!!! Ahead!!!'
email_body      = 'A non dead intruder has been detected and needs to be eliminated!'

# Credentials (if needed)
username = 'EMAIL_LOGIN'
password = 'EMAIL_PASSWORD'

# The actual mail send
server = 'smtp.gmail.com:587'

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name

post the complete traceback i.e. the error.

mime.multipart isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.encoders import Encoders

Study these examples in the Python 2.7 documentation.

Ok, I've done this and it worked perfectly. I had a little trouble with the Gmail server after on but it was a simple trick.


text:
Uno as a composite USB HID keyboard
I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.
What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)
Here is an example:
loop() {
  check_and_send_buttons();
  uint8_t inputByte = get_input(); //new
  handle_input(inputByte); //new
}

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?
I'm willing to also write new device driver for Linux if needed.

On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.
The main (328p) AVR interacts with it through the serial port.
You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.
So, to recap:
1) enhance the HID implementation to understand LED status commands coming from the PC
2) report such changes over serial
3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


text:
The Time are functions do not work correctly when the processor clock speed is set at 128K
How can I change The timers to work correctly when The processor clock is set to 128K instead of 16 M?
At present, using the delay function does not work correctly, The delay is far too long.

Your solution that makes perfect sense, however, it would be a mammoth task going updating the delay functions used in third-party libraries.

Surely, there must be some way to scale down the clock counters?

Add a new entry in boards.txt with the new value for f_cpu. Note that the timing functions will become far less precise at so low a speed.

I have tried changing bored.TXT, however, this seems to make no difference.

You have to select the new board that you have created in the Arduino IDE.

A commonly-used approach is writing an intermediate or surrogate delay function that your application calls.  That delay routine needs a way to know if the clock is slow (128 KHz) or fast (16 MHz).  If the clock is slow, divide the delay counts by 125 (the ratio of 16 MHz and 128 KHz) before calling the built-in delay().  [Or, adjust all your application calls to use numbers scaled down by a factor of 125, and in the surrogate scale them back up if the clock is fast.  This may give you better control than just rounding, truncating, or truncating up will do.]
For example, if you call the intermediate routine vDelay() and change your app calls from a delay(x) form to a vDelay(x) form, in the function vDelay(unsigned long ms) you will say something like if (ClockIsSlow) delay((ms+124)/125); else delay(ms);


text:
Can't upload my sketch from arduino IDE
I am using arduino uno and window7 64bit.I can't upload my program to arduino uno.When I upload it the warning message is show me.The warning message is"WARNING:Category 'USB' in library keyboard and mouse is not valid. Setting to 'Uncategorized'.What can I do?

Related (very similar) to How can I do this sentence show me in arduino.

Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ).
After doing so you can install the IDE again (i suggest to use .zip download of the IDE).
If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0
its possible that problem is caused by out dated executables after updating the IDE.
Hope it helps.

I seriously doubt it's Java. Please rethink your answer.

I had similar problem and cause was java


text:
Servo problem when use gps with softwareserial
When I use together servo motor and gps module with softwareserial , I found problem .Servo turing without signal.When I remove gps receive pin ,servo normally work. I use arduino mega 2560, ublox NEO6M and micro servo SG90 .Help me please!

Why are you using SoftwareSerial on a board that has lots of UARTs? Ditch it - all your problems will be solved.

What do you mean?

I mean why do you need to use SoftwareSerial? It is not good when doing anything else that relies on interrupts since it blocks the whole system when it's receiving a byte.  Just use the real hardware UARTs - that's what they're there for.


text:
How to get real time data from ardunio board using NodeJS and send to my remote server without the wifi module?
As the question, How to get real time data from ardunio board using NodeJS and send to my remote server without the wifi module.how to do this without any hardware.

It's impossible. You need at least some hardware to run Node.js. Your Uno cannot do that.

@EdgarBonet yes if you are connected to some hardware(computer), you can easily send the data

It is pretty easy to send data with the help of NodeJS. Here i attach the code.
var request = require('request');
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;

var serialPort = new SerialPort("COM5", {
  baudrate: 9600,
  parser: serialport.parsers.readline("\n")
});

serialPort.on("open", function () {
  console.log('open');
  serialPort.on('data', function(data) {
    console.log(data);
  });
});

serialPort.on('data', sendSerialData);

function sendSerialData(data) {
 request({
  uri: "http://127.0.0.1/write_data.php?value="+data,
 method: "GET",
  timeout: 10000,
   followRedirect: true,
   maxRedirects: 10
}, function(error, response, body) {
   console.log(body);
});

}

if your are connected to your system only you can do this , without any hardware it is not applicable


text:
Battery charger board with status interface
There are of course a lot of different battery charging boards, which can be used with the Arduino, most being TP4056 based. There are also a few battery charged boards with an on-board display showing the charge status and there are of course also a lot of programmable battery charger controllers (ICs) with status and control interfaces.
But is there any board available, not just the 'raw' IC, using a charging controller with a status interface, which allows access to the status interface from pins on the board? I can't seem to find anything.
For a battery powered Arduino project I am planning, it could at least be very convenient if I could query the battery charging status from software.

You could probably solder some wires to the status leds.

@Gerben Most of the charger boards don't even have status leds. I do however need more precision than just something like 'full' and 'almost empty'.

I know it's been asked quite long time ago, but still.  This is how would have I done the same, with the existing TP4056:

use an electric key in a form of mosfet transistor, controlled by digital output pin to disconnect your battery from the charging board once in a while (like every 5-10 minutes or so, depending on your project power drain) for a very short period of time to do the measurement below.

while the battery is disconnected, use an analog input pin of arduino with resistor-based voltage divider to see what's your battery voltage. Google for "measure voltage with arduino alone" for schemas and code, it's pretty straightforward.

For obvious reasons, you cannot do this measurement while having your charging board connected to battery, because you'll be getting voltage from the charger, and not from your battery. This is why we disconnected battery from the charging circuit in step 1.

Knowing

current voltage you just get from your battery
what is the voltage should be on your battery when it's fully charged
the voltage you allow it to discharge to
... you can calculate percentages

digitalWrite to that pin to enable mosfet to connect your battery back to charging circuit

You might consider a coulomb counter IC, it is designed to give you the state of charge of the battery. There is a module labeled "LTC4150 Coulomb Counter" that will do exactly what you want.

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


text:
How can I do this sentence show me in arduino
How can I do this sentence show me in arduino."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'

Umm..... you what?

Your question does not make any sense at all.

Your question is unclear.
Note that Mouse and Keyboard libraries are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro.   They are not relevant when using an Uno.

For Uno, it's LUFA: http://www.fourwalledcubicle.com/LUFA.php


text:
Using random() in a header file
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt = random(0, 101);
};

#endif

I have a header file with a struct like above but when I compile I get this error:
'random' was not declared in this scope
How can I use random() in a header file?

Add #include <Arduino.h> like this
#ifndef FOO_H
#define FOO_H

#include <Arduino.h>

struct Foo{
  int randInt = random(0, 101);
};

#endif

The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:
In foo.h:
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt;
};

extern struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr);
#endif

In foo.c:
#include "foo.h"

struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr) {
  if (!foo_ptr)
    return NULL;
  foo_ptr->randInt = random(0, 101);
  return foo_ptr;
}

random() is a function and therefore its return value cannot be used as static initializer.
Unless -std=c++11 or -std=gnu++11 are enabled.

It's valid C++ code I don't see why it would be different for an Arduino. The code works fine after I #include <Arduino.h>.

What is the outcome?  Did you try to compile exactly the code you put in your question?

I answered my question and it works as is. The only problem was that random() was defined in my header file so I had to include the Arduino library. Someone commented for me to do but it's gone now, I guess they deleted it.

With gcc, it works only with -std=c++11 or -std=gnu++11.
Probably the Arduino ide turns them on by default.

Maybe so, I didn't actually want to use random() as an initializer (I'm using it in another function within the header) it was just easier to use it in the initializer here (less code to display). It works for me though granted I am using stino with sublime text 3.

Arduino does in fact have -std=gnu++11 by default


text:
Error in Arduino Library file
I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.
Error

FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  Command_Packet::GetPacketBytes()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17:
  undefined reference tooperator new[](unsigned int)'
  FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  FPS_GT511C3::GetResponse()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735:
  undefined reference tooperator new[](unsigned int)' collect2.exe:
  error: ld returned 1 exit status

Library File (CPP)

byte* packetbytes= new byte[12];
byte* resp = new byte[12];

Not sure if having your files having an extension of .c.cpp would confuse things, it they're C++ it'd be more conventional if they were just .cpp.

Do you have a typedef for byte somewhere in scope at that location? byte is not a fundamental type and is usually typedef'ed to char or unsigned char.

What version of the IDE are you using?

I am using Arduino IDE 1.6.5. But then, I tried it with different version of IDE like 1.0.5, 1.0.6. It still shows the same problem. @Majenko

Try 1) removing the library and writing in the main sketch byte *test = new byte[12];. If this works the library has problems. Then 2) Try looking in the library. Probably something is redefining new

@frarugi87 Okay. I removed the library from the sketch and wrote the test code. It showed the same error. So I guess there is nothing wrong with the library. What next?

Then you have two ways to proceed: start with a working example (just a plain file with empty setup and loop, for instance) and gradually add every feature you need, until you find the broken one, or start removing features from your own one until it works. This way you'll be able to find the code that issues the problem

But there is no much feature in it. It is just the simple example code which comes with the library and the fingerprint scanner. https://github.com/sparkfun/Fingerprint_Scanner-TTL  Please go through this link and maybe download this library and try it out. @frarugi87

As I told you, my usual debug workflow is adding one feature at a time, then compile and see if it works. You said that removing the library leaves the error, so try starting from scratch and then adding code slowly. At present I can't download it.. Probably this evening I'll be able to do that...

The core of the problem is that the code is being compiled as C and not C++.
The error says 'new[]' is undefined at the link stage.  This is because the linker is not pulling in the C++ standard libraries.  The built-in function new[] it doesn't exist in C.
The filename FPS_GT511C3.c.cpp is the elephant in the room.  You could consider renaming it (and others) to FPS_GT511C3.cpp.  Although the plain Arduino IDE does not really have a problem with building them.
Another option might be to modify the new[] (and delete[]) for C's malloc() and free().  However this is only appropriate for the allocation of simple types (byte, int, etc).  If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.


text:
Inconsistent response AT command
I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters
Response
+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20
Expected response
+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,
Code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); //RX, TX

String inputString = "";
char inChar;

const int powerkey =  5;
const int statuspin = 6;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(powerkey, OUTPUT);
  pinMode(statuspin, INPUT);

  mySerial.println("AT");
  delay(2000);
  leserial();

  //TURN ON GPS
  mySerial.println("AT+ CGNSPWR =1");
  delay(2000);
  leserial();
}

void loop() {
  //GET LOCATION
  mySerial.println("AT+CGNSINF");
  delay(4000);
  leserial();
  delay(5000);
}

void leserial(){
  inputString = "";
  while (mySerial.available()>0){
    inChar = mySerial.read();
    inputString += inChar;
  }
  Serial.println(inputString);
}

Rookie mistake with serial reading. This explains: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

I want to know which clown first advocated blindly sending commands and delaying for 2 seconds to wait for a response. I see it so often it must be in some tutorial somewhere. Is it on Instructables? Youtube? Both are as bad as each other for spreading misinformation...

I managed to solve the problem, I edited the file "SoftwareSerial.h" and changed the size stated in constant _SS_MAX_RX_BUFF.
#define _SS_MAX_RX_BUFF 64 // RX buffer size

to:

#define _SS_MAX_RX_BUFF 128 // RX buffer size

I reached the conclusion that when I realized that the number of bytes returned in the function "mySerial.avaliable ()" was no more than 63 bytes.
I appreciate the support of all.

I am not sure if it is a good idea to patch the Arduino library as a workaround for your poor code.

Basically you're sending a command that gives a response, then waiting 2 seconds for that response to arrive (which is completely the wrong thing to do to start with).
You have to ask yourself: where does that response go when it does arrive, while it's waiting for you to finally get around to reading it?
The answer is: into a small internal buffer that is considerably smaller than the response.
Thus most of the response just gets thrown away because there isn't room for it.
Instead you should most definitely NOT delay for 2 seconds waiting for the response, and instead keep looking to see if there are any characters to read up until you reach the end of the line.
It's all explained here: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Thanks for the tips, really using the "delay ()" to simulate waiting for the command to be run completely is quite common in the tutorials on the internet. Everyone who saw makes use of this function! Your article helped me better understand the operation of the serial communication, but applied some concepts that you had not got success, the answer still comes incomplete. As you mentioned in answer, apparently the buffer does not contain the size of the command response. I increase the buffer size?

If you remove the delay and read the bytes as they arrive the size of the buffer is irrelevant.

I removed the sleeps but did not work. Any idea what could be? Thank you for your support.

If you show your new code we might be able to see where you are going wrong...


text:
MPU6050 safe to use with glue?
My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.
I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.
What I am wondering is if it is OK to:

cover the wire side of the board in glue from a hot glue gun?
                 Would this have any possible conductivity issues or risk damaging the wires or board itself?
If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

1) I do not see any problem here - I myself used hot glue to fix and isolate power source of robot from the copper side. It does not leak any (measurable by my tools) current, does not show any sign of detorations and works well both electrical and mechanical way. I used it only on copper side, where was risk of shortcuts and where were no heat dissipators (as it isolate also heat). But I think, that the MPU does not generate so much heat, to be worry about - body proximity and weather on summer would affect it more.
2) Hot glue is not as hot as soldering lead/tin so short contact with the MCU should not harm it. (You can shortly touch hot glue to manipulate it and not get burned, so it is not so hot). Anyway I would apply it as fast as possible and would leave it cool down before swithing it on (the working and the storing temperatures are different case). Be carefull with the wires, as the isolator can be melted, if heated by hot glue and moved at the same time. Also take in mind, that the hot glue should be little around the whole, to isolate from humidity. And that it would be complicated to solder anything after the glue is applied - so have all contacts (you may possibly need access) somehow lead out of the glue. And try the construction before applying the glue, to be extra sure, that nothing is missing and everything works.
I personally would place the MCU on some kind of PCB and solder the wires to the PCB organized the way the wires would continue to form "cable" and to have extra sure there is no force on the connection of MCU pins. Also I would fixed the whole cable to the PCB with something, so the solder itself is not under any force, as it is the most probabely place to broke there. An I would ensure, that the cable goes smoothly away from the PBC, as it would be bad, if it would be bent ower sharp edge at the place where it leave its glue support.

Brilliant response! Thanks so much! Regarding your last point, I was thinking the exact same. A small pit of pcb will provide me with somewhere to attach the MPU6050 but also to possibly have some sort of restraint on the cable, to, as you mentioned, take the force off the solder joint itself. Thanks again!

Would this have any possible conductivity issues

Nope.

or risk damaging the wires or board itself?

Nope.

If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.
This is known as "potting". You can get special potting compounds, but hot glue is just as good.

Thanks man! Would there be any chance that I could melt off the insulation on the wiring in doing this. Or would there be a special (maybe low temp) glue gun I should use?

The melting point of hot glue is considerably lower than the insulation of the wire.

@EoinClancy just avoid touching the wire directly with the glue gun tip, even if even this should not melt the insulation


text:
Arduino Nano (3.0) Use an USB Bluetooth stick
I was thinking to build a very small USB Audio Streaming device with aux output for an amp (I know they already exist, but I like the self invention). So I bought an Arduino Nano and a USB Bluetooth device with was originally for a computer. But I thought I might use it on the Arduino. After I removed the housing and soldered four wires onto the USB plug:
https://www.dropbox.com/s/ye5vveb98sfz1zq/IMG_20161030_132648_01.jpg?dl=0
I needed to know how to wire them:
https://www.moddiy.com/product_images/uploaded_images/patillaje-conector-usb.jpg
So I connected:

"1" to 5V+ on arduino
"2" and "3" need to be connected to txd and rxd on the arduino (but I don't know whitch way around)...
I read that I need to have 3.3v on "3" or the "+" wire but I have 5V Output on the digital Pins on the arduino (so I need some resistors, but I'm not familiar with calculating them).
"4" to gnd

Can someone confirm and / or provide some information for me to get this thing running (Bluetooth device enabled and functioning)?
Further steps would be:

coding the arduino to Use the Bluetooth module for audio streaming - preferrably three Channel.
configure the arduino to give the stream to an amp.

I know my knowledge of electronics is not very good and I need some education. If you can provide some good learning websites - feel free to suggest.

Do note that USB (universal serial bus) is not the same
As the other serial bus. USB is by itself -I dont think is hard-but it does,
Truly use a lot of layers  In the protocol you need to get correct to get.
I  give a link be low. to a USB host implemented in software for ATMEGA32
I see the source code is there-which you may try and modify for your uses,
Read the USB software is implemented in using the tx and rx type pins of ATMEGA 32 -(the pairs of pins corresponding to
D+,D-)- as they write on the page there its easy to write a keyboard driver (though not done).

Only a few componenets are used in the solution there.
https://courses.cit.cornell.edu/ee476/FinalProjects/s2007/blh36_cdl28_dct23/blh36_cdl28_dct23/

This is a suggestionfor a starting point-note that its low speed USB so maybe  its not fast enough for your device-but maybe you can find a workaround for this

Interfacing an Arduino with USB is already VERY hard. USB does not use the same Serial as protocol so don't connect it to Tx and Rx. The only way to interface an Arduino and an USB device is trough a USB shield, which is quite complex already.
Just for you information. USB uses 5V so no voltage divider is needed to reduce it to 3.3V. A voltage divider is pretty much 2 resistors in series where the original voltage goes in one end, the output voltages is between the 2 resistors and the other end is connected to ground. Read more about them here.
Now, communicating with Bluetooth is also complicated, but mix USB + Bluetooth and you get something ALMOST impossible (I hope the ALMOST is clear enough for any hatters). It is possible, but seeing you level of knowlage, simply don't risk having a severe depression trying to fingure it out!
In the end of the day, your plan of using that Bluetooth USB module is just going to be crazy complicated and big.
A more effective solution would be to use a module such as the HC-05 Bluetooth module. It is quite cheap if you get it from sites such as Amazon. Link here for this product on Amazon.com. It is designed with the Arduino in mind thus making programming easier. You project could also be a little smaller, because this module pretty much has the size of your Arduino Nano.
Hope it was helpful!

A lot you have said here is right, but there's a glaring error.  While USB uses 5v power the signalling is not 5v.  When a low-speed USB connection is crudely implemented in software using GPIO pins of a 5v MCU, voltage translation is required.  Of course it's not going to work for the purposes of the question anyway, but the data lines are not rated for 5v.


text:
Why change the variable content?
I don't understand why change uidList[reader] variable, when doesn't run more to the else. I use in this test only the "0" reader.
First loop go to the "else" and fill the uid to uidList[reader]. (good)
Second loop go to the "if" because the two uid is equal.(good)
I remove NFC and place the other, but the uidList[reader] updated immediately to the new UID, not in the "else". Never go again to else. Why?
#define NR_OF_READERS   2
byte* uidList[NR_OF_READERS];
MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
......
void loop() {
  ....
  delay(2500);
  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {

     dump_byte_array(uidList[0], 8);
     dump_byte_array(uidList[1], 8);

   if (mfrc522[reader].PICC_IsNewCardPresent() &&     mfrc522[reader].PICC_ReadCardSerial()) {

     dump_byte_array(uidList[0], 8); //WHY UPDATED HERE???
     dump_byte_array(uidList[1], 8);

     if (uidList[reader] == mfrc522[reader].uid.uidByte) {

        Serial.println(F("Same NFC"));
        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     } else {

        Serial.println(F("Other NFC in this reader"));

        uidList[reader] = mfrc522[reader].uid.uidByte;

        dump_byte_array(uidList[0], 8);
        dump_byte_array(uidList[1], 8);

     }

   }
}

void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
  Serial.println();
}

When I placed the new NFC in the reader, this debug appear on serial monitor.
 DF 6D 05 D2 00 00 00 00 //old NFC uid it's good

 AB 00 6C 02 F0 21 00 00

 FF 2C 02 69 00 00 00 00 //WHY UPDATED HERE???

 AB 00 6C 02 F0 21 00 00

Same NFC
 FF 2C 02 69 00 00 00 00

 AB 00 6C 02 F0 21 00 00

Thanks any idea.

The question isn't clear enough for me to understand what you are asking.

Why change uidList[reader] without "else". Without this: uidList[reader] = mfrc522[reader].uid.uidByte;

Well, it's easy, as you are using pointers. If the original place gets changed, you can see changed value because you don't have your own copy.
Your if statement is also wrong, as you are comparing two pointers here. They will be different at the first time comparation, but after the assigment they are unlikely to change.
The solution is using:
byte uidList[NR_OF_READERS][8]; // better to use some constant value instead of magic number

and memcpy for making a copy and memcmp for comparing its content. Both are from <cstring> include

Thx, you're right, but what is the solution? How do I compare the value, not the pointer in this code?

@Cipo You've to have your own space to store those values and you've to use the right functions for copying and comparing these values (or make your own). Added into the answer.


text:
How to detect whether connected to computer
I built a keypad that can adjust volume, play, pause, skip tracks, and control the arrow and num keys. It has some backlighting under the keys. I'd like to turn this off when the computer is off. Additionally, whenever the computer is restarted the device must be unplugged and plugged back in or the operating system will not register keypresses. Is there a way I can tell if the computer is on or if the device is connected?

Which arduino are you using?

Is the device USB connected?  Also,  by “Is there a way I can tell if the computer is on or if the device is connected?”, do you mean a way that you yourself can tell, or the Arduino, or your PC, or some combination?

It's an arduino micro on the inside and is powered and communicates via microusb port. Also, the preferable solution is that the arduino itself can tell if the computer is on as currently it requires no helper software to be running on the host computer and works the same on windows and osx (haven't tested linux yet).

Try to look in your bios or OS if there is an option to turn off the USB ports when shut down. Otherwise you will need to do it yourself: If your PC has PS2 ports, you can sense the +5V there and check if it is powered off at shutdown; otherwise you will have to open the PC and find some place which turns on only when the PC is on (e.g. the IDE cables coming from the power supply). Then you will have to setup a usb port powered by that 5V or with a transistor controlled by that voltage. I think that this will solve also the reboot problems (since the board will be initialized again at boot)

What USB library are you using? LUFA? As to the unplugging, you could try adding some delay inside the setup function.

@frarugi87, I could configure the the ports to turn off when shutdown but then it is impossible to use the ports to power other devices when the power is off.  Surely I should be able to wire into the the middle two cables and listen for the ACK packets right?

@Gerben I am using the keyboard function here as well as a modified version of this library for control of media keys and volume.

@amoose136     What is the colour of the USB port you have the device plugged into, also are you powering down the PC or putting it into sleep?

@RSM The port is non colored (USB 2.0). The computer completely shuts off usually but I still use other ports to charge things like calculators and phones from time to time.

@amoose136 Hacking the USB protocol is not a really good idea, at least for me. Too much complicated.. If you can't selectively turn off the USB ports (one of my mother boards had three switches to enable the feature on different usb ports) then I'm afraid that the easiest solution would be to add another USB port powered by the internal IDE connectors...

I think you can use the function USBConnected() to see if the host is present/alive.

@Gerben I would imagine that function should do it but it's not clear to me how to access that function. If I just call USBConnected(); it will say "function not defined at this scope."


text:
Reading two sensors at different frequencies... multiple Timer3?
Originally, I had a single sensor which I was reading at 100MHz. I used Timer3 and function attached to it to do both reading and writing of the sensor data (print to com port).
Now I have added another sensor which can only be read at half the frequency. I still want to be able to write data in the same format as before for both sensor data at 100Hz, with slower sensor data just being repeated twice.
How do I handle this? Do I use multiple Timer3 attachments at different frequencies? I am planning to have three interrupts.. 1st for reading sensor A, 2nd for reading sensor B, and 3rd for writing data.

which Arduino you are using?

I am actually using Teensy 3.1

The rule is:

One Timer, One Interrupt.

When the timer overflows it triggers its interrupt. It only has one. That interrupt then runs your ISR.
If you are using a library to provide abstraction from the timer registers then it is down to that library how it calls your ISR. It is possible for one to provide a mechanism whereby you can "attach" multiple routines to the same interrupt, but that is quite a lot of work and overhead for a simple timer library to provide, so it is highly unlikely anyone would ever bother.
So how do you do multiple sensor measurements from one timer? Simple: just do multiple sensor measurements. You don't have to restrict yourself to just reading one sensor within your interrupt - you can read as many as you like. There is just a couple of caveats though:

The whole ISR must take less that 10ms to run or it will overrun the timer overflow period.
You cannot do serial from inside an interrupt*

So in your interrupt you read the sensors and add their values to a buffer. Then in your main loop you read that buffer to send the data out through serial. You may want to set a flag in your interrupt routine to alert the main loop that there is data available, or implement a circular buffer which has an equivalent of a .available() function to see if there is any data to read from it.

*You can place data in the serial TX buffer but it will not be transmitted out of the TX buffer until after the interrupt routine has finished. If you put too much data in that TX buffer it will block indefinitely waiting for it to empty.

Conceptually, this is best solved by having an ISR which always reads the high rate sensor, but implements a toggle so that it only ready the low rate sensor every other execution.  On the times when you don't read it you could repeat a stored version of the last reading, though it would be more bandwidth efficient not to transmit that at all.
However, practically speaking this may not be the best choice.  The process of reading sensors often has a latency - typically to achieve the highest possible rate you would need to start the reading, and claim the result sometime later.  If your two sensors have distinct interfaces, or even if the they share an I2C or SPI bus, you may be able to start readings for both and then claim them with subsequent transactions after allowing them an overlapped measurement time.
It is also not clear that you are best to use an interrupt service routine at all.  If your MCU has nothing else to do, the most deterministic and ultimately fastest behavior on an ATmega might be to accomplish reading and direct (unbuffered) serial transmission within the main program loop, busy waiting at each phase.  This avoids not only the overhead of context switches when entering an ISR, but also a lot of the variability.  That would be doubly true if you can be transmitting the old reading while waiting for the already-triggered sensors to measure the next one.
However, you mentioned you are using a Teensy 3.x, which probably communicates natively via USB, rather than a serial UART.  That complicates things a bit - so called "serial" output flows in response to interrupts from the USB engine responding to the host, which is not really deterministic for you.  Fortunately, the Teensy is enough faster that you are less likely to have issues with running out of time, particularly when sampling at 100 Hz.


text:
two 7HC595 and only 12 outputs
im new to arduino and thinking to create a LED project.
im creating a LED project and i want to control 12 LED's. so i use two 7HC595 but problem i face is how can i only control 12 outputs ?
and i want to create multiple blink patterns with 12 LED, please be kind enough to provide blink patterns that i can modify and create different partners.
i have found many shift-out programs but i do not understand how to limit it to 12 outputs and create multiple blink patterns.
thanks

Other than only outputting 12 bits?

Just act like there are 16 leds, but keep the last 4 leds off all the time.

How can i code it. Any examples?

Is Google not working? Try here.

Thanks for the grate tutorial.  How can i make multiple blink patterns

Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need.  You never know you may expand the project.  Whatever is on the unused bits is irrelevant. they do nothing.

If you use 74HC595, you have to send data to all the bits no matter what. Even if you only want to change 1 bit, you have to resend the whole bit sequence.


text:
ESP-07s only connects to my wifi very occasionally
I've got an ESP-07s and I used an example code from the internet. When I power it and the program starts, it should just connect to my Wifi network. It has a simple webpage that should be locally accessible in my Wifi network.
I'll start by giving the code:
// Load Wi-Fi library
#include <ESP8266WiFi.h>

const char* ssid     = "MyWifiNetworkName";
const char* password = "MyWifiPassword";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output16State = "off";
String output0State = "off";

// Assign output variables to GPIO pins
const int output16 = 16;
const int output0 = 0;

unsigned long currentTime = millis();
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output16, OUTPUT);
  pinMode(output0, OUTPUT);
  pinMode(2, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output16, LOW);
  digitalWrite(output0, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  bool ledOn = true;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("~");
    digitalWrite(2, ledOn ? HIGH : LOW);
    ledOn = ! ledOn;
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.accept();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /16/on") >= 0) {
              Serial.println("GPIO 16 on");
              output16State = "on";
              digitalWrite(output16, HIGH);
            } else if (header.indexOf("GET /16/off") >= 0) {
              Serial.println("GPIO 16 off");
              output16State = "off";
              digitalWrite(output16, LOW);
            } else if (header.indexOf("GET /0/on") >= 0) {
              Serial.println("GPIO 0 on");
              output0State = "on";
              digitalWrite(output0, HIGH);
            } else if (header.indexOf("GET /0/off") >= 0) {
              Serial.println("GPIO 0 off");
              output0State = "off";
              digitalWrite(output0, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
Example
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
GPIO 16 - Status " + output16State + "
");
            // If the output5State is off, it displays the ON button
            if (output16State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("
GPIO 0 - Status " + output0State + "
");
            // If the output4State is off, it displays the ON button
            if (output0State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }
            client.println("");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

When I power it, one of the following cases happen:
Case 1
It just connects within, say 3 seconds. This is the desired case. It prints its IP address to the serial output, and when I navigate to its IP, the webpage loads and everything works. Of course, this is as how it should be.
Case 2
It keeps "trying" to connect, and after 1 ~ 2 minutes it is connected, but then the following weird thing happens. It seems to be connected, and when I look in the list of devices that are connected to my router (via router's web interface) it shows the ESP is connected, and has the IP 192.168.2.34.

As shown in my code, the ESP also prints its IP to the serial output as soon as it is connected. In the normal situation (case 1) this IP starts with 192.168.x.x, and this is expected, since all devices shown in the connected devices list have an IP that starts with the same range. But in this case, the IP shown in the serial output is something like "169.254.200.23". Also, the ESP's webpage is not accessible.
So: router shows ESP as connected, having IP 192.168.2.34, while the ESP itself prints a totally different IP (169.254.200.23). The webpage is at none of the given IP's acessible.
Case 3
It just doesn't connect. But I guess this could also be case 2 but then with an indefinitely "trying time" that I haven't waited.

Router settings have never been changed. Everything is kept default as it was when we got it from our internet provider.
I read on the internet an ESP can give problems when the WIfi channel 13 / 14 are used.
The router has set this to automatically choose a channel, and when I look in the router's web interface during a case 2, the channel was 1.
There's no MAC filtering.
The wifi signal strength at the location of the device is excellent.
The router sends both the 2.4 and 5 GHz signals.

It's a 1 / 10 chance that case 1 (desired) occurs.

I suspect insufficient powering

The ESP-07 has a tiny ceramic antenna and a socket (IPEX) for an external antenna. If you use an external antenna, there is a small capacitor on the board which has to be removed. Changing the antenna configuration may help if poor RF performance is the main issue.

Since you are joining an existing WLAN and not creating your own (soft) access point, I suppose you could try explicitly forcing the mode to station mode WiFi.mode(WIFI_STA); Also, this could be similar to your problem where it appears to attribute a 169.254.x.x address to a missing DHCP reponse. https://arduino.stackexchange.com/questions/78604/esp8266-wifi-not-connecting-to-internet-without-static-ip  so you could try giving it a static IP address in the right range.

@6v6gt The question shows an RSSI of -45dBm reported by the router, which is a good value. Poor RF performance is unlikely to be the cause of the problem.


text:
Is it possible to create a RS485 bridge over Wifi using 2 ESP07's
I've got a solar energy inverter that has a RS485 port for connecting a meter. You can place a separate energy meter in your distribution panel at home, that measures things like power usage, purchase and return of electricity. A two-core cable connects the meter output pins A and B to the RS485 port on the inverter.
A lot of meters on the market have the same protocol, not meaning it's just RS485 for transport but also the Modbus "format" of the data sent by the meter is understandable by the inverter.
I tested this provisionally with a meter that's recommended by the inverter manufacturer, and it works.
The problem is that the meter can only be connected to the inverter with a wire. There are no wireless options.
I want to create a solution for transporting data from the meter to the inverter wirelessly.
My idea is as follows:
At the meter's RS485 connection pins, I just connect them to ESP07 input pins. The ESP07 should read the meter's data and send it over Wifi to another ESP at the inverter side.
The ESP at the inverter receives the data over Wifi and generates an RS485 signal on two output pins that are connected to the inverter's RS485 port.
In simple terms: a wireless RS485 bridge over Wifi.
I cannot find a lot of resources on the internet about creating this by yourself. What I read somewhere is that there's a problem because RS485 is synchronous (think about baud rate), and Wifi is asynchronous.
What I'm thinking is that the ESP07 at inverter just independently generates a new RS485 signal based on the data it receives over Wifi. It acts like it's the meter.
The only thing is that there could be an overall delay. Am I thinking correctly?

Yes, that's possible. But you'll need both software and hardware, not only mcu chip, but also rs485 converter. Consider that on many occasions wired connection might be simpler, cheaper and more reliable.

Indeed I find internet sources speaking about specific hardware like a RS485 converter that is connected to the ESP. But I don't understand why you need specific hardware for this. In theory the signal is a voltage you can get as input to the pins on the ESP, in your software you can interpret the inputsignals on the pins?

rs485 uses relatively high voltage levels, so, no, you can't. If you really wonder you can just grab and read datasheet (e.g. max485) to see what it does and why you can't connect directly.

RS485 is 1 of many old standards meant to do different things. RS485 supports multiple drops over 1000+ meters of balanced pair wires designed for electrical noise rejection. Under known / well-understood circumstances, you could probably hack together something simple to allow the ESP processor to listen / decode the RS485 signal. But why take that chance when real RS485 interfaces are cheap & plentiful. Note, you should never (unless specifications state differently) drive a processor input higher then the processor's supply rail. Doing so may lock up or damage the processor.

You'll need RS485 to UART conversion modules on both the sender and receiver ESP07 units. https://www.dfrobot.com/product-2392.html


text:
127v/220v AC sensor - What's the role of this particular resistor?
After searching for a very long time for a 127v/220v (AC) sensor without using any kind of transformers, I found this very nice idea (image below):

I'd like to understand how this module works because I'll have to replicate it in my project without actually using it. I can already tell what's the role of every component, except for both resistors. The first resistor (10k) is placed between the capacitor's legs and, therefore, I'm assuming it's just a bleeding resistor. Am I right? The second resistor (220k), between the AC source and the optocoupler, I have no clue. I was also thinking whether I can improve this sensor by adding a rectifier bridge between the AC source and the optocoupler, allowing me to use a smaller capacitor to normalize the signal. Does that make sense? Thanks!

there is basically no creepage separation on that board, do it better if you DIY. all you really need is an LDR forming half a voltage divider being illuminated by a current-limited AC-driven LED. The LDR's slower illumination response eliminates the need for AC smoothing, and the luminosity will scale to volts.

The first resistor is working with the capacitor as an RC filter. Since you are sensing AC at 50~60Hz, you need this RC filter to get a constant output instead of a pulsed output. Remember your otpo-coupler has a LED (diode) inside, so it will only produce light when voltage is positive.
The second resistor is there to limit the current from your AC 220Vrms (which is 311V peak) so that is within the opto-coupler's LED forward current range. The voltage between your LED´s pins will always be it´s forward voltage (1.2V to 1.4V), so the resistor will bring down the 311V to 1.2 to 1.4V. Without this resistor, you would have 311V between the LED pins, and this would fry the poor thing.
The equivalent input circuit is something like this:

simulate this circuit – Schematic created using CircuitLab
Ok so how did they figure out the 220kOhms value?
First, take the worst case scenario: 220Vrms AC gives us 311Vpeak, and LED forward voltage is 1.2V.
So the voltage between the 311V and the diode is 311 - 1.2V = 309,8V
OHM Law: R = V/I        (R=resistance, V=voltage, I=current)
In this case, the current chosen for the LED was about 1.4mA or 0.0014A, so R = 309.8V/0.0014A
R = 221k Ohms. The closest we get to this is 220kOhms
With 127Vrms (179.6Vpeak), your LED current will be:
I = 178.4V/220000 = 811uA
I have simplified the calculations, because this is a simple case, but keep in mind that real life engineering calculations will be more complex than this.

keep in mind the top of a full AC wave is going to be higher voltage than the RMS

yeah, I forgot the basics of the basics, LOL. Fixed, thanks.

the cap also raises the RMS, so the imrpoved figure looks closer to an IR led current

Wow, that's a very comprehensive answer. Thanks! The moment you said "Remember your opto-coupler has a LED (diode) inside", I realized what the role of the 220k resistor was. I'm reading the Wikipedia page on "low-pass filters" right now to better understand the concept of the RC filter.


text:
State machinese for serial input
I am trying to control a servo using keyboard.
void loop() {
if (Serial.available() > 0) {
  x = Serial.parseInt();
  while(pos < 180){
  pos = x + pos;
  Serial.println(pos);
  myservo.write(pos);
  delay(100);
 }
  }
else if(Serial.available() > 0){
if(pos>=180){
  pos = 0;
  delay(500);
  myservo.write(0);

  }
  }
 }

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?

I don't understand why you use 2 Serial.available condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:
int pos = 0,x=0;
void loop()
{
  while (Serial.available() > 0) x = Serial.parseInt();

  pos+=x;
  if (pos>180) pos = 0;
  myservo.write(pos);
  Serial.println (pos);
  delay(100);
}

I should've been more clear. I want to rotate the servo from 0-180, and once the servo goes past 180 I want to reset it back to 0

Can you explain what is the serial input used for?

Getting input from the keyboard. I put in a value between 1-90 and It should rotate the servo that much. Once the servo rotates more than 180 degrees then it should reset to 0; I want to set it up so that immediately upon receiving input it rotates that much. Right now it waits until it resets to adjust the amount I rotate the servo

I think I got your objective. Answer updated

Thank you. I was complicating it with all the if statements and conditions. Your answer makes much more sense Thank


text:
Getting the DS18B20 detected and temperature read
I'm quite new with the electronics part of Arduino, but I thought that this was the basic way to get the DS18B20 temperature device hooked up. However, I can't detect it in my program using OneWire and DallasTemperature.
This is an image of my connections:

Basically my approach was like this:
Connect ground on ground on the DS18B20.
Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).
Between the 5V and the two yellow cables, I connected a 4.7K resistor.
Vdd on the DS18B20 is not connected to anything.
Anyone have any idea why this is not working as expected for me?
Thanks in advance!

I can't see the DS18B20 in your picture. Can you please sketch up (eg. on paper) your wiring? I can't quite follow your description.

Vdd on the DS18B20 is not connected to anything.

According to the datasheet:

When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground

Connect 5V from the Arduino to both DQ from the DS18B20 and Port 2 on my Arduino (the two yellow cables).

That means port 2 would always be high, right?

According to Temperature Sensor DS18B20 this is the wiring for non-parasitic power:

If you want the two-wire version (parasitic power) it would be:

I didn't get the parasitic power version to work, but the top image explained how the rasistor should be placed in the non-parasitic version, and that did the trick! Thanks a lot!

Glad it worked. The design is the standard "open drain" concept where the output is "pulled high" by the resistor, and the device drives it low when it wants to output a zero. This allows multiple devices to share that wire because it doesn't do anything any harm if multiple devices drive it low at the same time.


text:
Print when echo is read by HR-S04 sensor
I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.
The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?
int trig1 = 3; //Trig 1
int echo1 = 4; //echo1
int ECHO1;
double pingTime1;

void setup()
{
  Serial.begin(9600);
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

  while (ECHO1 == 0) //continuous loop until echo is HIGH
  {
    digitalWrite(trig1,LOW);
    delay(100);
    digitalWrite(trig1,HIGH);
    Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
   ECHO1 = digitalRead(echo1);
  }
  pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
  pingTime1 = pingTime1*1000; //convert microseconds to seconds

}

Umm, does your code wok in the first place???

To start with, you code isn't suppose to work. Here is a working code to start with (code below). You have a lot of mistakes so I suggest comparing your code to this one. Also, don't try to debug by adding a Serial.print(/*something*/); in your code.
For the time the echo is received is way too fast (under 0,001 seconds). I doupt you can use that for something useful. There is a way to calculate that using the millis() function, but it is quite complex for your project.
Here is a working code for the HC-SR04:
const int trigPin = 2;
const int echoPin = 3;

long duration, distance;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(9600);
}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 150) {
    Serial.print(distance);
    Serial.println("  cm");
  }
  if (distance > 150) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

I'm trying to record the system time when object passes by the sensor. I plan on having another sensor a little further up to record a second time. I plan on finding final time by difference then distance between sensors to compute speed.

A couple things:
1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()
2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.
3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.
4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.
I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.
Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.
// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');

I'm trying to record the system time when object passes by the sensor. I plan on having another sensor a little further up to record a second time. I plan on finding final time by difference then distance between sensors to compute speed.

Okay, you might want to clarify the question in your post. Just use an if statement to 'trigger' the sensors. (if within certain distance, record time)


text:
Record Ping time using ultrasonic sensors and calculate speed
I'm trying to find the speed of remote control toy car passing by two ultrasonic sensors. I need help on my code and suggestion on max speed car should go to record time. Opposite direction not accounted for and ideally the car would pass by both sensors without stopping. I know laser reading is better for this simulation but I need it for a presentation in two weeks.
Here are the steps I was recommended to use:

Get the duration of pulse for sensor 1 and convert to distance
if the distance the object is within the desired threshold (you detected something)
2a. record the system time at which object was detected
2b. start a loop to for sensor 2
Within the sensor 2 loop keep getting the duration/distance until an object is detected or too much time has passed
If an object is detected record the system time
Subtract the two system times (from sensor 1 and 2) and use that to determine object speed
#define sensor_distance .111 //distance between two sensors in meters
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

double first_time = 0;
double second_time = 0;
double final_time = 0;

double vehicle_speed = 0;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop() {

double ping_time(int trig1, int echo1, double first_time);
double ping_time(int trig2, int echo2, double second_time);

final_time = second_time - first_time;
vehicle_speed = sensor_distance/final_time;
}

double ping_time(int trig, int echo, double record_time) //function used to record time.
{
  long duration, distance;

   digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 35) {
    Serial.print(distance);
    Serial.println("  cm");
    record_time = millis();
    record_time = record_time/100; //Divided by 100 to get time in seconds

    return record_time;

  }
  if (distance > 35) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

You can try this, but I don't know if this gonna works or not since it is "imaginary-based"
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop()
{
    if (ultraSonicdetect())
    {
        while (ultraSonicdetect(trigPin1,echoPin1)); // wait the car pass ultrasonic 1
        first_time = millis();
        while (!ultraSonicdetect(trigPin2,echoPin2)); //wait the car approach ultrasonic 2
        second_time = millis();

        //here you can calculate the speed, time needed to travel from ultrasonic 1 to ultrasonic 2
        //can be calculated from
        //(speed = second_time - first_time) / sensor range
    }
}

bool ultraSonicdetect(int trig, int echo) {
   long duration;
   float distance;
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration * 0.034) / 2;
   if (distance<35) return true; else return false;
}

In THEORY, this code should work. If there are any mistakes, please notify me and not hate on me. I did not have the equipment at hands to test the code in real life.
Chears!
const int trigPins[2] = {3, 5}; //trig1 and trig2
const int echoPins[2] = {4, 6}; //echo1 and echo2

const int sensorDistance = 7;   //7 is the cm distance at which the sensors distant from eachother in CM

void setup() {
  pinMode(trigPins[0], OUTPUT); //set trig pin 1 as output
  pinMode(echoPins[0], INPUT);  //set echo pin 1 as input
  pinMode(trigPins[1], OUTPUT); //set trig pin 2 as output
  pinMode(echoPins[1], INPUT);  //set echo pin 2 as input

  Serial.begin(9600);
}

void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    unsigned long currentMillis = millis();               //time when the passed the first sensor

    while (getDistance(1) == false);            //wating car to pass the second sensor

    unsigned long endMillis = millis();                   //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0;        //because 1000ms = 1s

    float s = sensorDistance / timeSeconds;       //speed = distance / time

    Serial.print(s);
    Serial.print(" cm/s");
    Serial.println();
  }
}

bool getDistance(int sensor)
{
  //max range is 200cm, if further, it will go a little wild

  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low
  delayMicroseconds(2); //wait for 2 microseconds
  digitalWrite(trigPins[sensor], HIGH); //set the trigger pin to high
  delayMicroseconds(10); //wait for 10 microseconds
  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low

  long duration = pulseIn(echoPins[sensor], HIGH); //read the echo pin and calculate the duration in microseconds

  long distance = duration * 0.034 / 2;

  if (distance < 50) //50 is a reasonable distance other wise it might be innacurate
  {
    return true;
  }

  else
  {
    return false;
  }

}

So my output has just been 0 cm/s so far. I'm still trying to figure that out. Also, why is your sensor distance zero? Also, how can getDistance() determine which sensor you are using?

I included an input for the sensor. I dont call getDistance(), I have to say getDistance(sensor 0 or 1). 0 is the first sensor and 1 is the second. The reason I do this is to use an array for the pins thus saying which sensor I want.

How far are your sensors from each other??

Replace timeMillis / 1000 with either timeMillis / 1000.0 or timeMillis / 1e3.

the sensors are 7 cm apart from each other. I input 7 for sensorDistance. Now highest reading is 7 cm/s.

New edit to the answer following @EdgarBonet comments, what are the results now?

my results look like:
73.68 cm/s
7000.00 cm/s
777.78 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
inf cm/s
I assume the first number is the real speed

What color are the pins of your sensor? are they gold is yellow or more silvery aluminium colored?

silvery aluminum colored

The reason for all the numbers is that when a stationery object is in front of the sensors, it prints out random numbers. I need to fix code to take time of transition recorded.


text:
Arduino programmers for hire?
How do I best connect with Arduino programmers who are willing to design small projects for some extra cash?

are you talking about Free lancer   ?

The Arduino Forum has a Gigs and Collaborations section where such questions are welcome.


text:
Using Analog Pins for Power
I'd like to power something needing 5V DC using the Arduino Uno analog pins. Specifically, I'm following the "Fun Plug-in Hack for Arduino UNO" section of this Adafruit tutorial. It states:

"If you set analog pin A3 to an OUTPUT and HIGH and A2 to an OUTPUT
and LOW you can power the RTC directly from the pins!"

It doesn't seem to work, so I try this with a multimeter hooked up to A2 & A3:
void setup() {
  pinMode(A2, OUTPUT);
  pinMode(A3, OUTPUT);
  analogWrite(A2, LOW);
  analogWrite(A3, HIGH);
}

void loop() {}

I only measure ~0.8V, trying 2 boards including a brand-new unboxed one. This is the same whether the board is powered via USB or via 9V battery in the barrel jack.
But I can measure ~5V from those pins if I set the "ground" pin as INPUT_PULLUP (using the built-in pull-up resistor) instead of OUTPUT:
void setup() {
  pinMode(A2, INPUT_PULLUP);
  pinMode(A3, OUTPUT);
  analogWrite(A3, HIGH);
}

void loop() {}

I don't believe Adafruit is wrong, since conceptually it makes more sense to set both pins to OUTPUT, with one being HIGH and the other being LOW. So what am I doing wrong?

What were you trying to power?

@Majenko DS1307 RTC

The analog pins are only analog inputs but digital outputs (and inputs too). You use digitalWrite() to control a pin's HIGH or LOW state.
ànalogWrite() is for use with the PWM pins (I hate the name the chose for that function it's so wrong on so many levels).
Also this powering trick only works for things that need very small currents (< about 20mA) since that is the maximum an IO pin can deliver.

Incidentally, you can use analogWrite() on a non-PWM pin, but it's either fully on (analog value >= 127) or fully off (analog value < 127). The macros HIGH and LOW are 1 and 0 respectively, so that equates to "fully off" and "fully off" on a plain non-PWM pin.


text:
How to restart void loop if condition is met
This should be a quick question.
I'm trying to figure out how I can restart void loop() if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.
 void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    while (getDistance(0) == true && getDistance(1) == false);
    unsigned long currentMillis = millis(); //time when the passed the first sensor

    while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

    unsigned long endMillis = millis(); //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

    float s = sensorDistance / timeSeconds; //speed = distance / time

    if(s>=7 && s<=10) // for red to turn on
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 2); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low

    }
    else if (s<7)
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 4); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low
    }

    delay(2000);
  }
}

loop() is just called in a... loop. Hence, if you just return from it, it will be called again.

Of course you could mean you want to restart loop() halfway through the code in loop, in which case you should use the return; statement,  which will cause the current function call to exit immediately and return control to the calling function.  In the case of loop() this will cause it to be restarted.

When programming with arduino IDE, you declare 2 functions, setup() and loop().
Before compilation, arduino IDE basically expands to :
int main(void)
{
    /* run the Arduino setup */
    setup();
    /* and the event loop */
    while (1) {
        loop();
    }
    /* never reached */
    return 0;
}

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.

To expand on what jfpoilpret said setup() and loop() are called by the code you can't see in every program.  setup() is called once and loop() is called in a while(true) loop until the program crashes or the universe ends.
To call you code while a condition is met you could either wrap it in a loop or an if, within the loop() function, so something like this:
void loop ()
{
    if (s > 10)
    {
        // Your stuff....
    }
}

This will only call your code IF s > 10.  Something you need to watch for is ensuring that there is some code that can cause s to be greater than 10.
You can also move "// Your stuff..." into a function of its own
void MyCode ()
{
    // Your stuff ...
}

and then call this function from inside the if statement.  This makes you code easier to read and easier to fix.
If this answer wasn't what you meant then feel free to comment and I'll see if I can come up with a better answer.

I hate to bring this up, but I've now been programming for 58 years. One curious and often overlooked feature of the C & C++ languages is the GOTO keyword. It can be very useful. My second language was FORTRAN I. I know, now I'm relegated to the 9th circle of he|| where the miscreants are frozen into glaciers head down with their legs protruding?

Regarding the last bit, perhaps not at the hands of the arduino.cc people, since  bothered to mention goto in the official documentation.

goto has legitimate uses, but there is no point in using it if you instead can simply return: “_ If there is no cleanup needed then just return directly_”.

frozen into glaciers head down ... that's one way to keep a cool head


text:
Serial.read() is getting a whole string rather than just a character?
From the arduino documentation, the Serial.read() function is supposed to return a single character at a time from incoming serial messages. So if I program the arduino with the following:
#include "SPI.h"

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

void loop() {
  if (Serial.available() > 0) {
    char data1 = Serial.read();
    Serial.print(data1);
  }
}

And I open the serial monitor and send "Hello, World!" I would expect the received message to be the individual characters printed one at time but instead I get back the whole message. So what gives? What am I not understanding?

... That you're printing characters until no more are available.

But shouldn't they be printed one at a time?

They are being printed one at a time. But how fast can you read?

Oh I see. I stuck a delay() in there and It makes more sense now. I am not that smart, apparently.

You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.


text:
Possible to create IP-to-USB HID (keyboard) device using Arduino?
Is it possible to create an IP-to-USB HID (keyboard) using Arduino?
I'd like to connect an Arduino to my network using Ethernet, and then send it commands using TCP/IP and have those commands translated to USB HID and sent as keystrokes to the connected PC.
I've found a few articles discussing USB HID emulation using the Arduino Uno (see http://mitchtech.net/arduino-usb-hid-keyboard) but it refers to using GPIO pins as buttons.
Am I correct that this might work if I use an Arduino Uno and then purchase an Arduino Shield Ethernet?  (seems a bit expensive, but is this the cheapest option?)
Thanks in advance!

And it's not the cheapest option.
You might want to check Arduino HID first, to see which type of Arduino can handle HID. You could also buy an Arduino Nano and arduino ethernet module on eBay (which should be around $10) but might take a 15-30days shipping.

Yes, it is perfectly possible.
You ideally need an Arduino with a direct USB interface, such as the Leonardo. Then you can just access the Keyboard object to send the keystrokes to the PC.  How your receive the data through Ethernet is entirely up to you. A simple TCP interface may be easiest - open the connection with whatever telnet-like client and whatever you type gets sent through.  The trick will be getting it into character-at-a-time mode.

Thanks for the information!  So I would need a Leonardo and then connect my own USB connector to the I/O pins?  Also, what would be the cheapest way to add the Ethernet connection?

No, with the Leonardo you just plug the USB cable into the on-board USB socket. No need to do anything dodgy with GPIO pins. The cheapest ethernet is probably using WiFi with the ESP8266.

What about the Leonardo ETH version?  (I'm not too found of wireless, usually)

Perfect board. Has everything you need. Just plug in the USB and Ethernet cables and write a sketch. Nothing else needed.

Thank you so much!  Any recommends for a case?

Nope. Never used a case on an Arduino before.

authors: Иван Крафченко


text:
What is the timing between reset and avrdude/spi communication? (re: avrdude problem)
I'm trying to troubleshoot an issue with avrdude involving a Raspberry Pi and a transistor to control the reset pin on an Arduino Pro Micro (atmega32u4).
Where can I find information on the reset/programming process for the atmega32u4 or Arduino?  The atmega32u4 data sheet provides a bit of information but some of it is above my head.
For example, avrdude (and other programmers) require the microcontroller to be reset before uploading a new program or interacting (ie. fuses) with the chip.
Why is this?
The atmega32u4 specifies a minimum reset pulse of 400ns (ie. high to low to high again), but how long afterwards is the chip available for communication to avrdude?

avrdude interacts with a program that is running on the microcontroller (bootloader)

For AtMega32U4, a hardware reset, plus setting the PE2 to low will put the chip into hardware bootloader activation(HWB). Search HWB in the datasheet for more info. Arduino Micro uses DFU bootloader which take some time to be ready after reset, you can find out more about AVR DFU implementation here.

https://arduino.github.io/arduino-cli/latest/platform-specification/#1200-bps-bootloader-reset

It all depends on how you are programming - are you using ICSP? Or DFU? Or the Arduino bootloader? It all makes a difference.


text:
Why does oscilloscope trigger look shaky when using delayMicroseconds?
I'm new to electronics but I have a Rigol DS1054Z oscilloscope and I'm experimenting to help learn.  I've created an incredibly simple sketch using an ESP32 and Arduino IDE:
void setup() {
  pinMode(32, OUTPUT);
}

void loop() {
  delayMicroseconds(10);
  digitalWrite(32, LOW);
  delayMicroseconds(10);
  digitalWrite(32, HIGH);
}

However, the square wave is incredibly "shaky" or unstable looking.  Why is that?

is it jitter? the code is not the right way to create a perfect wave.. try a PWM signal

@ArduinoFan: Yes, this is jitter.

Have you tried no interrupts to see if that fixes the problem? https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts/  DSO "Trigger Mode" set to "Normal"?

See https://arduino.stackexchange.com/a/37393/6628

The display moving is what we call jitter. It is normal with the Arduino  and expected. The pulses are not even because of the background tasks such as the interrupt service routine (that does the millies etc whether you use them or not). When an interrupt occurs it causes the processor to stop, save its state, do a new task, then restore its state and continue. During the interrupt service routine (ISR) the processor uses time to execute instructions, this delay causes the jittering. Trust your scope, as usual it is correct. If you use one of the timer outputs the jitter will go away because they are not normally adjusted the just keep going. PWM is one of the more common modes of doing this but there are many others you can also use.

This isn't an answer, but you could compare it to hardware PWM to test the limits of the rest of the system.
Simple ESP32 PWM per https://www.electronicshub.org/esp32-pwm-tutorial/
int freq = 48000;
int ledChannel = 0;
int resolution = 8;  // 48000*2^8 < 80Mhz on channel 0 per https://www.electronicshub.org/esp32-pwm-tutorial/

void setup() {

  ledcSetup(ledChannel, freq, resolution);
  ledcAttachPin(32, ledChannel);
  ledcWrite(ledChannel, 127);
}

void loop() {
}