text:
Library to send large amount of data over 433 MHz
I am trying to communicate between two Arduinos using two RF 433 MHz modules (transmitter receiver). I found that the library Wildewire.h allows a maximum of 77 bytes so is there any another library that allows to send a more than that?

Send many packets of 77

That's too abvious but I want to send the message all at once or at least if I can't to know what's the maximum possible I can send at once

Edit a link into your question to the source for this library so the someone can look at it to understand why it is limited to 77 bytes. [][][][] You do realize that with the small RAM size of almost all of the AVR processors used on Arduino boards that the idea of sending huge packets of data around between these limited resource devices makes little sense. Even the "big" ATMEGA2560 part used on the Arduino Mega board has only 8K bytes if RAM.

433 MHz isn't really suited for moving large amounts of data, but if you want to make the most of it, send multiple packets as previously suggested.

@MichaelKaras - you seem to be overlooking that packet sizes on limited bandwidth links are kept small for a good reason - and doubly so if they need to be retransmitted in the likely case of failure.  The answer is not to muck about with that, but to send multiple packets as previously suggested.

@ChrisStratton - I am not overlooking what you are saying at all. I am just ALSO pointing out that that the small RAM size of a typical AVR would play into packet size limitations just due to implementation restrictions. Another factor that also has to be considered here are legal limitations of how long you can be in active transmit mode on the unlicensed low power device (LPD) 433MHz band. This article provides some detail:  https://www.edn.com/electronics-blogs/eye-on-iot-/4437311/Using-433-MHz-for-wireless-connectivity-in-the-Internet-of-Things. Packet sizes play into this in a big way!

The small RAM has nothing to do with it, because it's much larger than the sizes contemplated and because that usage is easily configurable to fit the tradeoffs of an application need.  As for your 2nd point, that would be just a re-interpretation of the fact that narrow bandwidth leads to small packets, except that you are largely misinterpreting the regs, which are more about duty cycle than duration.  The actual reason for brief duration is that you want a chance to move a useful chunk before interference ruins the whole packet.

Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.
I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

As being a full message
As being a start of message (message overruns 64 bytes)
As being a mid message
As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.
You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).

Thank you for your respond but at least if I can know what's the maximum possible I can send in one transmission

Well your question stated that 77 bytes was the maximum and that is reasonable for radio transmission packets. I'm not sure I've addressed your concern so maybe you can elaborate?

Even Ethernet can only send 1522 bytes at once. Packets are everywhere. You need bigger than one packet, then send multiple packets. Simple fact of life.


text:
Why does Arduino Tone example with 8 ohm speaker make USB port fail?
I'm using an Arduino Nano and attempting to run the basic sample program at:
https://www.arduino.cc/en/Tutorial/toneMelody
When I build the circuit they way they show (extremely simple) using an 8 Ohm speaker and connect the power to USB the Nano begins to power (never fully powers up) and then the USB port fails (I believe as a protection mechanism).

Is the schematic provided with that sample incorrect?
They say it can be used with an 8 Ohm speaker but they show it hooked up with e piezo.
Here are the comments from the Sketch:

Is it possibly overdrawing current with the 8 Ohm speaker?
Is the circuit incorrect in some way?
NOTE: Without the speaker connected the Nano powers up with no problem. I am also building other circuits with the Nano and they work fine.

If you have a pure resistive load of an 8 ohm resistor across a 5V voltage source a current of 625 millamps would flow -- USB by standard provides 500mA (https://superuser.com/a/690077/546860), but since the current is coming out of the digital pin in this case, you will overload your pin which has a max of 40mA (https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations). I'm also interested in how this is supposed to work (inductive load?).

Thanks for you input.  Because I was searching around and reading before I tried the simple circuit, I thought maybe it was wrong too.

Try putting a capacitor (maybe 470uOhm) in series with the speaker. This prevents DC voltage to pass through. But also keep in mind, that the pins are not designed to drive a speaker directly. It can work (tried it myself one time), but it is risky. The piezo doesn't let any DC current pass (since it is basically a capacitor with a special dielectric material in it), so it isn't critical.

@chrisl Thanks for hints. I think I'll be safe and use a piezo.

The circuit depicted is for a piezo and is reasonable for that use.  Using it with a low impedance magnetic speaker is incorrect (you'll find this is not the only glaring omissions in Arduino materials).  However, that does not explain the USB failure, since the current drawn by shorting an I/O pin does not exceed that limit.  Perhaps the speaker was accidentally connected between supply pins, rather than as shown.

someone should write an answer :-)

@Juraj - no factual, credible cause of the observed behavior has been identified.  Comments have made it clear what would be better, but there is no explanation of the failure that headlines the question.

@ChrisStratton If you write up your answer I will set it as answer since it was actually correct (see comment on other answer).  Also, I am still curious though (and afraid to try) about what would happen now that the circuit is fixed, if I re-connect the 8 Ohm speaker which some say will draw far too much current.  Is that true?  Will it draw to much current on the Arduino pin?  Is it unsafe to actually use an 8 Ohm speaker as shown?  Or can you do it?

As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.
In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.
There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.
One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).
The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.
When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.
Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.
So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.
A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.

This was an older question and I obviously figured out the issue to resolve the problem, however, you explained the difference between the piezo and the speaker and that was something I thought was incorrectly explained in the original Arduino.cc post so I marked this as answer.  Thanks.

Thanks for marking my answer. But I am still curious: did pin 8 survive and did you find the reason for the USB-port failure?

Pin 8 did survive. I found an old piezo buzzer on an old motherboard and desoldered it and used it for my tests.  I never did try the 8 Ohm speaker.  The real problem (as I mentioned) was that I had wired one of my pushbuttons back to 5V instead of GND.  However, everything worked (including that mis-connected pushbutton) until I added the piezo buzzer.  When I did that I was seeing the Nano get kicked off the USB port (thankfully) so it didn't burn out the Nano or the USB port of my computer.

The USB +5v opens to protect your computers from the connected device trying to draw too much current. The pin driver may have burned out, or it may, in fact, have delivered an excessive current (even if not the full 625 mA) but have been saved from failure by the USB supply having opened soon enough.

No.  The stated circumstances of this question would not draw more current than a USB protection device permits, because I/O pin output drivers are practically rather weak.   That would only happen if something about the actual situation were not as stated.

@ChrisStratton To close the loop on this-when I went to add the piezo I noticed that one of my input buttons was wired improperly.  The input button had 5v incoming and then a line to 100K resistor and out to ground. As I looked closely, I saw that the line from the resistor to ground was actually back to 5v (missed ground hole on bboard, hit 5v). There are 3 input buttons & other 2 were correct.  Also this input button still worked though wired improperly.  However, when the 8Ohm speaker was added (between pin 8 and ground) only then did I see this odd behavior of USB port fail (protection).

source: Stack Exchange

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

sort: votes


text:
How does an LED in an LED-strip like WS2811 know when it should be on or off
I was experimenting with an Arduino board and an LEDstrip WS2811
it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?

You might find the explanations at https://www.edn.com/design/led/4438797/Tips-and-tricks-for-driving-WS2811-LED-strips---Part-1 , https://forum.arduino.cc/index.php?topic=365474.0 and the datasheet https://cdn-shop.adafruit.com/datasheets/WS2811.pdf useful.

after a reset, the WS2811 saves the first colour value it receives and passes the rest of colour values to its output   ..... imagine a line of people and a deck of coloured cards ... the people are instructed when you hear the bell (that is the reset), keep the first card you receive and pass any other card to the next person ... use you imagination to fill in the rest

The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.
So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

EDIT:

but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.
Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.

Clear answer, but How does it recognize the first led?

@AnneMabellon  I added extra explanations for this. I hope it is clear now.

The LED units don't have any unique addresses of their own, instead they are indexed by their position in the string of LEDs. When you feed data into the first LED, you put the entire sequence of color values into the first one. It will then set its own color to the first one in the sequence, and then output all the rest to the next LED in the series.
None of the LEDs actually "know" where in the strip they are located, they only take the first value that comes in and set their own color to that value, and then output the rest of the values to the next LED in the series.

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


text:
How to track a pressure sensor from analog inputs?
I am a beginner with arduino. I have been researching pressure sensors composed of 2 conductors that sandwich a layer of velostat. My understanding is the velostat when compressed creates resistance between the conductive plates meaning when stepped on the charge decreases. I wanted to inquire about a wiring scheme for connecting these sensors to my analog inputs of a arduino nano with ideally 8 sensors connected to the 8 analog inputs. What is the wiring scheme? I would like to detect a gradation in sensitivity as best as possible for tracking someone applying pressure to that sensor. I have not built the sensors yet so that aspect of the project is open ended. Thanks for your attention in the matter. I am new to the world of electronics so please explain in elementary terms.

It is not really clear, what exactly is your question here.
You are correct: The resistance of the velostat goes down, as pressure is applied to it. You have to build a voltage divider with the sensor and a normal resistor. The best value for that resistor highly depends on the sensor you build, because the way and the size you build it will control it's resistance. Then you can feed the middle pin of that voltage divider to an analog input.
The precision depends on many factors, including the sensor itself and the noise, that gets introduced into the analog input. Try and tweak your circuit, until it suits your needs.

What exactly is a voltage divider?

Two resistors in series, often (and also in this case) one of it with a variable resistance. One side connected to the supply voltage, the other side to ground. Then the voltage at the point between these resistors depends directly on the ratio of the resistors values. This is often used for analog measurement. For further explanation google voltage divider. There are many tutorials and sites on the web, that explain this perfectly.


text:
Read pc volume percentage?
is there a way to read the current pc volume? This is going to be a part of a project that I have in mind that is essentially reading curent pc volume value and giving it an RGB value (green=>30, yellow=<30>60, red=<60) and lighting up an RGB led accordingly.

Please describe a little better what you want to read. pc = PC = Personal Computer (maybe with Windows)? Do you want to read if the volume slider is set i.e. to 30% or do you want to "read" how much noise comes out of the speakers?

I'm voting to close this question as off-topic because the capabilities of PC operating systems are not on topic here - and doubly so when the operating system in question has not been identified.  Needless to say, if you obtain a number by some means, you can transmit it to your embedded system.  And no, Nick Alexeev, this is not an Arduino question either - it is a PC operating system question, and at presently too broad even for a site about those.  SE policy prohibits the migration of unanswerable questions and requires that they be closed at the source.

You guessed it the system is windows and I want to read the precentage that windows has in volume manager I know there are many HID librarys that can increase or decrease the volume but I have not seen any that can be used to pull the value. @chris Stratton https://www.reddit.com/r/ProgrammerHumor/comments/2zp22c/how_im_sure_most_firstposters_on_stackoverflow/

No, I stated the operating system was unspecified.  And irrelevant here.  How to obtaining settings information for PC operating systems, regardless if they are identified or not, is not a a permitted topic on this site, full stop.  SE sites are not traditional discussion forums, they are an intentionally narrow format, strictly separated by topics not permitted to overlap.

Well aren't you just a perfect specimen of the SE community and reputation

It seems like SE is not right for your needs.  And indeed, there is more than does not fit within this system than the very narrow set of things which does.  But that's what this is about.  Doesn't mean I agree with that, but it is what it is.  There's a whole remainder comprising merely... every non-SE site on the global Internet to satisfy other needs and approaches.

The easiest way would be writing a program, that runs in the PC and sends the current volume and any change to the Arduino via Serial. Investigate how to interface system volume in the PC with your chosen programming language (for example python).

@ChrisStratton This question is perfectly on topic. It may not be worded well, but the question is essentially "Can the Arduino be programmed to do X" where the answer is "No, it can't, but there are other routes you could investigate".  The question is not "How do I program the PC to do X", which would be off topic.

@Majenko - sorry, but you are completely wrong.  Read the question again "is there a way to read the current pc volume?"  That has nothing to do with Arduino.  If the poster could do that, then sending the result to an Arduino could be on topic, (if utterly trivial) but that's not the question that was asked.  Instead, a question about an unidentified PC operating system was asked.

@ChrisStratton Whatever. If my reading of the question is so wrong, how come my answer is accepted as correct? If you paid attention to the kind of questions asked here you'd know that people often ask about the Arduino querying information from the host PC in this kind of manner. You have to learn to read between the lines with Arduino users.

This question had a number of well deserved close votes from people who actually understand the rules of this site.  Those should not have been wiped out.

@ChrisStratton: when the highest rated guy on the site (by 2x) corrects you about site practice, consider he might know somewhat more than you about the site...

There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.
HID is a protocol which (when used as a keyboard) allows you to send keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.
You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).
Some pointers:

C# get master volume level/precent
Windows 7 Master Volume
Arduino: Sending and Receiving Multi-Digit Integers

There are external devices that show the volume, but you need a driver for that. I don't know if there is an open source driver which you could adapt to send the volume via a serial port to the Arduino.
The Windows PowerShell has the possibility to get the volume and transmit it to a serial port. You could do that a few times per second. In linux it might even be easier, a bash script with gawk with "amixer sget Master".
Another problem is to select the right serial port for the Arduino. I don't know how to automatically select the right port.


text:
What is a simple way to measure the ambient light?
I want to install some LED stripes on my motorcycle, i.e. as brake light and indicators. I use WS2812 LED stripes which can be very bright - especially with many LEDs on at the same time.
I want to measure the ambient light so that in the bright sun I can light the LEDs with, let's say, 100%. But in the night maybe just with 30% intensity. I want to detect the ambient light to change the intensity.
I don't need high resolution and I don't need high speed. If the ambient light is measured i.e. once per second with 4 bit resolution that would be already good enough.
Which ambient light sensor (or photo diode or whatever) makes sense for this little project and how to connect it?
Does it make sense to use more than one light sensor for a better average ambient light value (just in case one sensor is in the shadow, another in the sun)?
I found these sensors form a Chinese supplier:
https://www.banggood.com/CJMCU-9930-APDS-9930-Digital-Proximity-And-Ambient-Light-Sensor-For-Arduino-p-1103139.html
https://www.banggood.com/GY-49-MAX44009-Ambient-Light-Sensor-Module-For-Arduino-p-1196674.html
But an I2C interface seems to be overkill for my simple project.
Any suggestions?

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

#define LDRpin A0
unsigned int LDRvalue = 0;

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

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

Note that swapping the LDR and the resistor might make the wiring easier: you will just have to pull a single wire from the LDR to the Arduino, as the ground connection can be made through the chassis. And even if you pull two wires, you have an extra safety: an accidental short from the GDN wire to the chassis won't fry anything, whereas a short from +5V could burn the Arduino.

Thanks, that looks good. I just checked and it seems there are many types of this sensor 5506 / 5516 / 5526 / 5528 / 5537 / 5539 / 5549. The main difference seems to be the resistance. Min is 2~6kOhm for the GL5506, max is 45~140 kOhm for the GL5549. I guess they will all work with the correct fixed resistor. Any recommendation?

Different resistance + LDR combinations will all work - it's just a matter of what sensitivity it gives you to different light levels.

You can also use an LED. Connect the LED and its resistor between two port pins. Then, when you want to measure ambient light in your program, do this:

Make sure any pullups/pulldowns are disabled.
To discharge the LED, start with switching it on for a short moment (a clock cycle is enough) by setting the pins to output and setting anode high and cathode low.
Reverse the polarity by setting the anode pin low and the cathode pin high.
Set the cathode pin to input.
Using a timer and a pin change interrupt, measure the time it takes for the cathode pin to become low.

Since the capacity of the LED varies with light intensity, the time it takes for the LED to discharge through its resistor and the pin resistance is is an indication of light intensity.

Thanks, I saw that example. But somehow I think let LEDs do what they are designed for and use other parts (i.e. LDR from the answer above) for what they are designed for...

You're saying the functionality of a LED changes with external light intensity? What? How does that even work? Can you provide more details, or a citation, because this is really surprising to me.

@Benubird Turns out, there is a Wikipedia article about it: https://en.wikipedia.org/wiki/LED_circuit#LED_as_light_sensor

@Benubird In fact any semiconductor junction will function as a (poor quality) photodiode. There is nothing special about light emitting diodes, except that for non-light-emitting diodes that are not designed to be photodiodes, the junction is covered in opaque material to prevent the photoelectric effect happening. In some semiconductor devices, the opaque material is simply black paint which can be scraped off to make a photodiode!

@alephzero Wow, that is very cool! So OP doesn't need a separate sensor, they can just repurpose their LEDs. I wonder if anyone has built some sort of prepackaged auto-adjusting LED


text:
Need help with converting Celsius to Fahrenheit in the code
I'm new to Arduino and trying to figure out how to convert Celsius to Fahrenheit with the parameters listed below. Do I need to create a separate file for the calculations? If so, can someone help me on how I can go about doing that?
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  TEMPERATURE = dht.readTemperature();
  HUMIDITY = dht.readHumidity();
  Serial.print("Temp: ");
  Serial.print(TEMPERATURE);
  Serial.println(" celsius ");
  Serial.println(" ");
  Serial.print("Humidity: ");
  Serial.println(HUMIDITY);
  delay(2000);

  //Built In LED
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(250); // wait for a second
  digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  delay(250);
}

If dht.readTemperature() and dht.readHumidity() return floating point numbers then you may want to change TEMPERATURE and HUMIDITY to "float" instead of "int".

If you are using the Adafruit DHT sensor library, then you can get a
Fahrenheit reading by passing true as an argument to
readTemperature(). C.f. the comment in the source code. For
example:
Serial.print("Temp: ");
Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
Serial.println(" deg. F");

Note that this library offers also the conversion functions
convertCtoF() and convertFtoC().

You could add a function to your sketch.
// Celsius to Fahrenheit conversion
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

Then add this code to your loop().
Serial.print("Temp: ");
Serial.print(Fahrenheit(TEMPERATURE));
Serial.println(" fahrenheit ");


text:
Robot car speed issue

If I'm connecting it in this way I have no issue and I can control the speed.
here is a video

const int speedMotorA = 9;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

void setup() {
  Serial.begin(9600);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
}
void loop(){
  TurnMotorA();
  TurnMotorB();
}

void TurnMotorA() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
}

void TurnMotorB() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
}

now I'm trying to expand my mini-project with servo and ultrasonic sensor
with this code and wiring, I have tried many ways to control speed but it's not working properly while increasing speed motor A respond but motor B stay off till I reach maximum speed 255 motor B start working.
here is a video

#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;

const int laser = 8;
int distance = 0;
const int speedMotorA = 9;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

int hitlaser(){
  digitalWrite(laser, HIGH);
  delay(200);
  digitalWrite(laser, LOW);
}

void setup() {
  pinMode(laser, OUTPUT);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
  myservo.attach(5);
  myservo.write(65);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);
 digitalWrite(laser, HIGH);
 if(distance<=50)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(300);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(5);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
}

int lookLeft()
{
    myservo.write(150);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
    analogWrite(speedMotorA, 0);
    analogWrite(speedMotorB, 0);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, LOW);
  }

void moveForward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, HIGH);
    digitalWrite(motorPin4, LOW);
}

void moveBackward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, HIGH);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, HIGH);
}

void turnRight() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, HIGH);
  delay(300);
  moveForward();
}

void turnLeft() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, HIGH);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
  delay(300);
  moveForward();
}

update :
after removing servo from the project it seems working but how can i use servo with this project
Thanks to  Majenko♦
update 2
after attaching servo to pin 9 i can now controle speed but still some issues as when Robot car have obsticles it should make backword >> issue is >> one motor only go backword!.
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;

const int laser = 8;
int distance = 0;
const int speedMotorA = 11;
const int speedMotorB = 3;
const int motorPin1  = 4;
const int motorPin2  = 7;
const int motorPin3  = 12;
const int motorPin4  = 13;

int hitlaser(){
  digitalWrite(laser, HIGH);
  delay(200);
  digitalWrite(laser, LOW);
}

void setup() {
  pinMode(laser, OUTPUT);
  pinMode(speedMotorA, OUTPUT);
  pinMode(speedMotorB, OUTPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  pinMode(motorPin3, OUTPUT);
  pinMode(motorPin4, OUTPUT);
  myservo.attach(9);
  myservo.write(65);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);
 digitalWrite(laser, HIGH);
 if(distance<=50)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(1000);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(5);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
}

int lookLeft()
{
    myservo.write(150);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(65);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
    analogWrite(speedMotorA, 0);
    analogWrite(speedMotorB, 0);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, LOW);
  }

void moveForward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, LOW);
    digitalWrite(motorPin3, HIGH);
    digitalWrite(motorPin4, LOW);
}

void moveBackward() {
    int Speed = analogRead(A2);
    Speed = Speed*0.24926686;
    Serial.println(Speed);
    analogWrite(speedMotorA,Speed);
    analogWrite(speedMotorB,Speed);
    digitalWrite(motorPin1, LOW);
    digitalWrite(motorPin2, HIGH);
    digitalWrite(motorPin3, LOW);
    digitalWrite(motorPin4, HIGH);
}

void turnRight() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, HIGH);
  digitalWrite(motorPin2, LOW);
  digitalWrite(motorPin3, LOW);
  digitalWrite(motorPin4, HIGH);
  delay(300);
  moveForward();
}

void turnLeft() {
  int Speed = analogRead(A2);
  Speed = Speed*0.24926686;
  Serial.println(Speed);
  analogWrite(speedMotorA,Speed);
  analogWrite(speedMotorB,Speed);
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, HIGH);
  digitalWrite(motorPin3, HIGH);
  digitalWrite(motorPin4, LOW);
  delay(300);
  moveForward();
}

Appreciate your support

Some ground connections are missing.

yeah but in the video, it's connected, forgot to add this on drawing.( servo ground wire)

The problem here is a conflict of resources.  Both the Servo library and the PWM for pin 9 require the same timer.

The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You should choose a different PWM pin (not pin 10) instead of pin 9.

for servo I'm using only one pin myservo.attach(5);

myservo.attach(8); (I have changed it to pin 8 but still not working).

Ok i have removed servo from the project and it seems working , so how can i fix this issue and let it work with servo .. Question updated Thanks ! @https://arduino.stackexchange.com/users/4143/majenko

Another update2 please check

@ahmedyounes It doesn't matter where the servo is. It's the pin 9 pwm for the motor you must change - like my answer states quite clearly.

yes I'm not using pin 9 for motor anymore, I updated the code in the update section, the only issue is when it's doing backward , one motor only works will upload video

If you cut out all the code from your program except code to make it always run backwards, does it work?

Thanks alot Majenko its working now , is there any documentation for these pins disabled when servo library is used ?


text:
Waterlevel sensor disrupts PH reading
I have a water level sensor and a PH sensor connected to my nodemcu via an ADS1115 . When I insert only the PH sensor into the water then everything works fine. But when I insert the waterlevel sensor into the same container the PH sensor seems to shortcircuit and I get 5V no matter the actual PH level. Is there anything im missing or a way to prevent that from happening?

You might find this video very interesting: www.youtube.com/watch?v=udmJyncDvw0

That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.
There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.
There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221

You could also electrically isolate the water sensor so it's neither powered nor grounded unless you are actively reading it.


text:
Adafruit Feather unable to upload code
I am using Adafruit Feather RFM69HCW Microcontroller. I am having difficulty uploading code in any Adafruit Feather boards. We have a project that is live on the field and it needs code changes. I have tried everything from holding the reset button while uploading, uploading the basic Blink function, changing USB micro cables, using different Adafruit Feather Boards.
However, I am assuming it has something to do with the Adafruit drivers.
I would really appreciate it if anybody can help me figure out the problem here.

Doesn't adafruit have a pretty good support forum?

You don't say which board you have (M0 or 32u4) and you don't tell us what error you are getting.

difficulty uploading code ... this is useless information


text:
How many times can I upload a program or sketch to my Arduino Uno Clone Board?
I'm about to work on my very first project using arduino (I'm just about to buy one next week), and one of our professor says that we can only upload a program or sketch in an Arduino Uno Board for approximately 8 times. He also added that if we're using a clone version, it'll can only last for 2 sketch uploads. Is this true or is he bluffing? Thank you in advance.

I've been flashing sketches to one particular Nano multiple times an hour as I build and test and I have been curious about this over the past few days myself. I knew it would be at least in the 100s of times but wasn't sure how many. Thanks for asking.

Time to question that professor's credibility. The program will be flashed into to the ATMega328P's internal flash memory, and flash will survive a few thousand write cycles. Even more for EEPROM. STMicro quotes "10K to 100K cycles" (http://www.st.com/resource/en/application_note/cd00165693.pdf)

Related: SPIFFS on the 8266 wear-levels, so if you're saving 3KB with 3MB free, you can save 1024X before the first overwrite (in theory, 512X on average w/o block overlap), which means millions of saves.

@jsotola unless Google shows you this question was already answered on SE, please don't tell users to Google (source: FAQ)

This is the ASE equivalent of fake news.

I think it’s all bluff, I’m using a clone and I’ve uploaded well over 100 sketches to mine. (Anyways, they are pretty darn cheap)

He's talking complete and utter gibberish.  To quote from the ATMega328P datasheet:

High Endurance Non-volatile Memory Segments

32KBytes of In-System Self-Programmable Flash program
  Memory
1KBytes EEPROM
2KBytes Internal SRAM
Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
Data Retention: 20 years at 85°C/100 years at 25°C(1)
Optional Boot Code Section with Independent Lock Bits

In-System Programming by On-chip Boot Program
True Read-While-Write Operation

Programming Lock for Software Security

So you have at least 10,000 uses out of it before it starts to go flakey.

I would say he has at least 10K uses.

The way Flash memory works, as it ages it takes longer for a page to be erased. The 10,000 is the minimum expected number of erase operations on a page before the time taken to erase could start to exceed a pre-defined (manufacturer specified) threshold. So yes, you would expect to get more than that number (it's the minimum guaranteed), or it just take a little longer to erase pages.

In practice, I was reusing an Arduino Uno and constantly making small tweaks to the code.  Uploading again takes long enough that this is not even worth worrying about.  You are far more likely to goof up the board in some other manner if you are soldering or bending wires.  Also, when doing Arduino... the boards are so crazy cheap (particularly if you can move down to a MiniPro 5V) that the main thing you need to worry about is to just be careful when soldering the sensor/IO stuff.  The board is extremely reliable, and you can just replace cheaply if you ever have any doubts about the board.

whenever you get a talk about storage "wearing out", just keep in mind that it's generally this: 1) You have to "stressfully" blast whole areas full of zeroes and then write the ones over that.  2) Solid State storage usually has complex wear-levelling algorithms to minimize the impact of this.  3) It's a cheap Arduino.  4) The language is a subset of C++, so you can mock out a testing framework to fully test before it hits hardware; to limit unnecessary pushing of untested code into the hardware.

here is a simple example of mocking out the board so that you can just unit test it locally under Linux (compiled with GCC), rather than constantly pushing to
hardware to test.  The basic idea is to make a framework that looks like as much of the Arduino calls as you actually make from your code:  https://github.com/rfielding/octaveRounder/tree/master/test

@Rob generally you don't even bother with 4 (except for unrelated reasons) because of 3

I would suggest sending him anonymously a data sheet for the microcontroller with the pertinent parts highlighted the same section Majenko showed.  Since the clone units use the same micro and same other components why will it not last as long. I have one I have been flashing for over 6 years and no problems. I use it to test my code, it is connected to a USB and generally no other hardware. I do not think he is bluffing he took a SWAG and missed it badly. I suggest you continue to check his statements throughout the course.

I have firmware 94% flash - it took me a week to kill it. And this is a second device I killed this way. It's a Pro Micro clone. So I suggest solder a pcb with a reusablle port to change the card

it doesn't matter how much space of flash you use. it is only about the count of writes (erases really). and I doubt you did 10000 uploads, your Pro Micro has some other problem

Yes, you were right :)


text:
Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi?
Basically I want to wire a Wheatstone bridge style load-cell into a moving trolley and transmit the data to a remote workstation so I can get real-time feedback about the loading conditions.
Do I need to have a full board riding on the trolley that is wired in between the Wi-Fi transmitter and the bridge amplifier or is there a way that the current variations from the bridge can be read directly by the Wi-Fi transmitter and relayed to the remote in some translatable format?
The trolley design is extremely streamlined and it would be a bummer to have to add more than minimal electronics to make this happen...

the ESP8266 has the same kind of IO as an UNO, more or less, it's all you need.

There are small packages out there with built in WiFi.  Node MCU is one of them, however its analog to digital conversion isn't up to the task of measuring bridges.  If you go that route you'll need to add a ADC to the Node MCU which will increase the total package size.


text:
Creating formatted String (including floats) in Arduino-compatible C++
I'm using a Mega2560 and a generic SSD1306 OLED display with the Adafruit_SSD1306 (and by extension, Adafruit_gfx) library.
I need to print a bunch of float values (ranging between 30.0 and 99.9) to the display with exactly one decimal place of precision. The catch is, the Adafruit library doesn't have a printf() method, only one that takes a single ready-to-print string.
Here's an (obviously non-Arduino) Java-like example of what I'm trying to accomplish:
String foo = String.format("%.1f, %.1f\%", temp1, hum1);
// "display" is my instance of Adafruit_SSD1306
display.print(foo);

So... how can I do something similar in Arduino-compatible C(++)?
Note: for this specific program, I have (relatively speaking) RAM to burn, so I really don't care if whatever library I use to generate formatted Strings is particularly efficient (as long as it isn't leaking). If it wants to use 4k of RAM and 80k of flash to format a 20-character String, so be it.

use dtostrf() function

Normally for formatting strings I'd suggest the venerable snprintf and similar functions. However, on an 8-bit Arduino when you're using floats that's not an option: the function that does all the formatting for this family if functions has had floating point support surgically removed from it. This is to make the function a fraction of the size so it's not as bloaty in small microcontrollers.
I believe there is a float-capable version somewhere on the internet that could be somehow installed, though I have never looked into doing that.
Instead you need to do the formatting of floats manually.  Everything else can be done with snprintf, but the floats need to be done separately.
Fortunately there's a function specifically for formatting a float into a character array (C-string), called dtostrf and is used thus:
float myVal = 23.49173783;
char *buffer[10]; // Enough room for the digits you want and more to be safe
dtostrf(myVal, 9, 1, buffer);

The first number in the parameter list is how many characters you want to have in your output, including the . and any leading -. Any extra characters are padded with space.  The second number is how many decimal places.  If the first number is negative the value is left-aligned. If it's positive it's right-aligned.  So the code above would give you:
〿〿〿〿〿23.5␀

(Note: I am using 〿 to denote a space character.) If you used -9 you'd get:
23.5〿〿〿〿〿␀

You can, of course, feed that created string into another string using snprintf and the %s placeholder.
char buf2[32];
snprintf(buf2, 32, "The temperature is: %s\r\n", buffer);

buf2 ⇒ "The temperature is: 23.5〿〿〿〿〿"

If you want to trim the string down to just contain the number portion and lose the spaces it's best to left-align it with a negative width, then change the first space to a ␀:
char *space = strchr(buffer, ' ');
if (space != NULL) {
    *space = '\0';
}

The Adafruit_GFX class has two methods named print() and
println(). These behave exactly like Serial.print() and
Serial.println(). Specifically, when printing a float, you can provide
a second argument telling it the number of decimal places you want after
the decimal point:
display.print(temp1, 1);  // 1 digit after the decimal point
display.print(", ");
display.print(hum1, 1);  // ditto
display.print("%");

Background: the reason these methods behave like the ones of
Serial is that both Adafruit_GFX and HardwareSerial inherit them
from the Print virtual class.

it is not ideal for right aligned float numbers on LCD

@Juraj: That's right. However, the format used by the OP in his question ("%.1f, %.1f\%") doesn't do any kind of alignment. Thus I assumed that alignment is not a requirement.

One can use the String() type initialization to convert any number, including float to String. For example to convert 3.14159 simply type ⤵
float num = 3.14159
String str1 = String(num, 1) // 3.1
String str2 = String(num, 2) // 3.14
String str3 = String(num, 3) // 3.141

To the right of the comma is the number of decimal places one wants the string result to have. It has a lot of functionality but that's one of the overloads. You can see them all here!
To see this code working on a .ino sketch check out this GitHub repo
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries


text:
warning: variable 'b' set but not used
I got the following error:
warning: variable 'b' set but not used.
I think I do a really small thing wrong but I can't figure out what it is.
#define array_size(array) ((int)(sizeof(array) / sizeof((array)[0])))

typedef struct Boid {
  unsigned long start_animate_time;
} Boid;

Boid boids[4];

Boid create_boid() {
  unsigned long start_animate_time = 0L;
  Boid b = {start_animate_time};
  return b;
}

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

  boids[0] = create_boid();
  boids[1] = create_boid();
  boids[2] = create_boid();
  boids[3] = create_boid();

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i]; // <<<<<<<<<<<<< this line!
    b.start_animate_time = 456;
  }

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i];
    Serial.println(b.start_animate_time); // BUG always 0
  }
}

void loop() {

}

flock_01_ino_debug.ino:28:10: warning: variable 'b' set but not used
  [-Wunused-but-set-variable]
       Boid b = boids[i];
            ^

I get Symbol 'I' could not be resolved. Change I to i.

@Jurai No idea how that became a capital since I copied pasted all code. I guess it is a safari auto correct that happened after I added // <<<<<<<<<<<<< this line! Since that is the only thing I added in the browser.

C++ is not Java. You can't just assign structs like that - it copies them (if anything).
Boid b = boids[I]; // <<<<<<<<<<<<< this line!
b.start_animate_time = 456;

Instead just access the array slice directly:
boids[i].start_animate_time = 456;

And later on as well:
Serial.println(boids[i].start_animate_time);

Basically, you create a "Boid" variable called "b", copy the content of boids[i] to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:
Boid *b = &boids[i];
b->start_animate_time = 456;

Or use a reference:
Boid &b = boids[i];
b.start_animate_time = 456;

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...

Thanks, I always struggle with references and pointers since my lack of experience with them.

Or you can use some C++11 features:  for (auto & boid : boids) { boid.start_animate_time = 456; Serial.println(boid.start_animate_time); }  (two loops are not needed here at all)

@KIIV Indeed - though be careful using auto - the meaning seems to change from C++ version to C++ version. Like they can't make their mind up what it's for.


text:
Output voltage of PIR sensor

Case 1
I am measuring output voltage of PIR sensor, I am getting 3.3v
Case 2
I have connected a resistor and a led to output of PIR sensor. Now when I measure voltage at the output pin of the sensor, I am getting 2.04v only.
In case 2 as the output voltage is dropped, it is not able to trigger a high state to arduino pin.
Where am I going wrong? What shall I change?

I believe you have to remember that the LED itself has a voltage drop of about 1.7V, so 3.3 - 1.7 = @1.6V.  Plus the voltage drop over your resistor depending upon the size it is.  So that voltage drop should be expected.

The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.
Either increase the resistor value, and accept that the led is less bright.
Or use a transistor to drive the led.
Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR


text:
Background "static" on side of TFT screen?
I recently bought an XC4629 128x128 TFT screen and noticed that failing to initialise a background for the screen produced this RBG static.
A red line drawn on the screen without a background:

The problem, however, is that when I did initialise a background, the "static" remained on 3-4 pixels down the side of the screen:

Here is the code I used:
 #include <TFT.h>
 #include <SPI.h>

 #define CS   10
 #define DC   9
 #define RESET  8

 TFT myScreen = TFT(CS, DC, RESET);

 void setup(){
   myScreen.begin();
   myScreen.background(0,0,0);
 }

 void loop(){
   myScreen.stroke(255, 0, 0);
   myScreen.line(0, 128, 128, 10);
 }

Is this a problem with the screen itself? I have searched around the internet and have found no similar issues. Due to the behaviour it seems like an code issue but I have made it as simple as possible and experimented and only found it goes away if I remove the signal and just have the screen on backlight only. I also double checked that the wiring was all in the correct slots (both referencing the code and the datasheet for the screen).
Many thanks in advance.

It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.
So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting.  Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.
I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.


text:
HEF4094 with 12v Vcc
Using old NXP HEF4094BP shift register chips, for the reason of fixing some old hardware. These chips were popular in the 90's because they could accept 3-15V VCC and directly drive series+parallel LED chains. Think: gas station price signs, etc.
I'm green. Using this post and the 4094 datasheet, I've successfully modeled your typical shift register count-to-100 binary, with an LED on each SR out. Powered by 5V, works great. This was phase 1 for me.
For phase 2, I powered the Arduino via 12V (via p30, Vin). Still supplying 5V to the 4094 (Nano pin 27 output), works great.
Phase 3, I need help. I remove the 5V jumper that was from Nano pin 27 going into 4094's VCC pin. In it's place, I run 12V directly from the (regulated) PS and I get NO LED output.  I know I haven't burned anything out because at 12V I get brief "flashes" when I'm "plugging" in the 12V power supply. I can revert to 5V VCC input and it works fine as before.
I've read the datasheet 3X and it's not clear how the chip's output pin voltage is managed when you alter the VCC to be higher (is it limiting current or voltage on the outputs?)

The part of the datasheet you need to understand is this bit:

That's the input logic levels, and as you can see they vary depending on the supply voltage.
At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.
The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.
These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.

THANK YOU for the perfect answer. I get it -- signal requirements "scale" relative to the VCC so I need to boost the signal lines after leaving the Arduino. I haven't done this type of thing yet, but I've read all the SparkFun transistor tutorials more than once, and just need to "do" it. Cheers.

Not that I would change my design (I actually need to follow this approach to salvage something cool), but out of curiosity does anybody make a chip that functions how I was assuming things worked (5V high input expected regardless of VCC into the SR)? I'm surprised by the variety of SRs one can choose from, and from a novice user POC they're a pretty fun way to learn!

@Crossfit_and_Beer I'm not sure if there's a single chip solution off hand, but normally people use a low voltage shift register coupled with a higher voltage IO driver chip, such as the ULN2803. There are LED driving shift registers with constant current sinks available which run off 5V or 3.3V and can sink 12V happily, as well as I2C equivalents, both constant current and open-drain (TLC59116).  I am not aware of a single chip solution though, but I will have a google around for you.

Ah, a ULN2803. I'll look at that next, TY.    Yeah I suppose if one were creating a fresh design, I2C (or the ws2812s) would be the way to go - solving the problem neatly for nearly any type of signage.


text:
Is it possible to print a custom object by passing it to Serial.print()?
I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

There is a class called Printable. If you inherit from that, and implement the size_t printTo(Print& p) function, your object can then be passed to the print functions:
class myClass : public Printable {
    private:
        int _val1;
        int _val2;

    public:
        myClass(int v1, v2) : _val1(v1), _val2(v2) {}
        size_t printTo(Print& p) const {
             size_t r = 0;

             r += p.print("One: ");
             r += p.print(_val1);
             r += p.print(" Two: ");
             r += p.print(_val2);
             return r;
       }
};

Then:
myClass ob(4, 5);

Serial.println(ob);
=> One: 4 Two: 5

Majenko, thankyou very much for your answer. I got it working. Just little comment on your code. I think instead of "size_t printTo(Print& p)" should be "size_t printTo(Print& p) const". Thankyou

I just copied and pasted the prototype from the header.

I was getting an error of not overriding virtual function. Once added the const, all ok.

Ok. I have modified it for future reference

How are we supposed to know these things? The arduino documentation is quite... lacking... to say the best. Digging through the source code on github?


text:
Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone?
I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using ARF7044A bluetooth module if that matters. Any help would be appreciated please.
Arduino to Android: Working
Android to Arduino: Not working.
Here is the wiring:
Here is the code:
char state;
void setup()
{
pinMode(8, OUTPUT);
Serial.begin(9600);
}

void loop()
{

  if(Serial.available())
  {
    state = Serial.read();
    Serial.println(state);
  }
  if (state == 'a')
  {
    digitalWrite(8, HIGH);
  }
  else if(state == 'b')
  {
    digitalWrite(8,LOW);
  }
}

Please show us your wiring

@chrisl Hi, I have added the wiring to the post.

To me this looks like the same issue I encountered some time before.
In my case the SPP-C bluetooth device was able to receive from my computer but the communication did not work the other way around.

@Kwasmich hey thanks. I think my android phone might actually be the problem here. Brb gonna try another phone.

On a second look: You also don't need a voltage divider on Uart_tx.
The other one is fine because you want to use the Arduinos 5V TX pin on the 3.3V Uart_rx pin. But you already have a 3.3V output on your Uart_tx and then dividing it further down to 2.2V will be too low for the Arduino RX pin to recognize a signal.

@Kwasmich the divider doesn't work as a divider with the shown resistors in the reverse direction.  However it does with the output of the USB serial.

The reversed order makes it even worse. You have a 1:3 ratio instead of 2:3. So from your 3.3V only 1.1V reaches the RX pin. Just directly connect Uart_tx and Arduino RX. 3.3V won't harm a 5V tolerant pin.

Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.
Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and
To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip.  Further, when the Arduino's Serial is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).
The actual circuit you have looks more like this:

simulate this circuit – Schematic created using CircuitLab
Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle.  Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.
Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see here).
Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.
The 3.3V transmitted by the Bluetooth module is a little under the official threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some upward level shifting.  There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.

For a reliable solution you must move the Bluetooth device to pins other than digital 0 and 1 and use a software serial instance to communicate with it.
Digital pins 0 and 1 are for communication with the host computer, and the USB-serial chip is permanently wired to them, even if you are not trying to communicate with the computer.
There is on many boards a series resistor which allows an external circuit to overpower the USB-serial, but your mis-conceived level shifter has enough resistance itself that it is not able to do this.
Fortunately, while ill-conceived the level shifter is still wired with the idea that the Arduino side is the higher voltage one, so while it adds some load to the Bluetooth, it mostly just adds series resistance.  If the Arduino pin were an ordinary high-impedance once, this would probably still work.  But instead it is one which the USB-serial is trying to control through its own comparable value resistor, and the result is an invalid logic level or a tug-of-war which the USB-serial wins.


text:
Assigning Pointers to arrays - incorrect results?
I'm trying to build a transmission frame for a workshop library for the Arduino Uno. I have the byte frame inside an array, give it to another function that builds a bit frame and then want to transmit that bit frame.
When I try to print out the arrays using the serial monitor, I get the correct results for the entire byte array and correct results for the bit array up to a certain point. However, since my output (that I'm checking using a logic analyzer) had also more incorrect values when trying to print the values, I suspect it might have to do with timing issues from my transmission and Serial.print.
I thus tried to make another pointer (in the code below frameCheck) to print that out after I'm done transmitting my frame, which still leaves me with results that are different from what my logic analyzer tells me from a certain point onwards.
My byte array is as follows:
10100101  // Preamble
10000000  // First line of my image
00100000
00010000
01000000
00000000
00000000
00000000
00000000  // Last (8th) line of my image
11110000  // Checksum

These values are also represented in the bit array (before assignment to what in my code be called _frame as well as after that). However, when I read the values from the logic analyzer, the checksum is transmitted as 11111111 instead of 11110000.
Here is my code in the .cpp file:
Transmitter::Transmitter()
{
  [...]
  _frame = new uint8_t[90];
  frameCheck = _frame;
  [...]
}

[...]

int Transmitter::prepFrame(LEDBitmap image) {
  if(_busy) return -1; //no Data can be sent right now since the transmitter is already busy
  if(!_pin) return -2;
  /** construct the frame that is to be transmitted
    *
    * frame structure is
    * 1 byte preamble (0xA5) | 8 byte payload | checksum
    *
    * the image will be transmitted in rows
    * with one row being one byte
    *  1  2  3  4  5  6  7  8   <-- 1st byte
    *  9 10 11 12 13 14 15 16   <-- 2nd byte
    * 17 18 19 20 21 22 23 24   <-- 3rd byte
    * ...                           ...
    */
  uint8_t size = 10;
  uint8_t frame[size];
  uint8_t checksum = 0x00;

    for(uint8_t h = 0; h < image.getHeight(); h++) {
      uint8_t value = image.getBitmap()[h];
      checksum = (checksum + value) % 255;
      frame[h+1] = value;
    }

    for(uint8_t h = image.getHeight(); h < 8; h++) {
      frame[h+1] = 0x00;
    }

  // building the frame
  frame[0] = PREAMBLE;
  frame[size-1] = checksum;

//The byte frame "frame" is correct at this point

  _frame = buildBitFrame(frame, size);

//The frame built by this function (see below) as well as the bit frame "_frame" have the correct checksum

  frameCheck = _frame;  // <-- This is the checkFrame which I print in my .ino which gives me false results.

  // set the transmitter into busy mode so the idle pattern will no longer
  // be transmitted but instead the frame will be sent out.
  _busy = true;
  _pos = 0;

  return 1; //preperation was successful
}

uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t bitFrame[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; // <-- This frame is correct as well.
}

void Transmitter::transmitBit() {
  if(_active) {
    // Preperation
    // only change the state when the manchester bit is completely transmitted.
    if(!_manHalf) {
      if(_busy) {
        // if there is currently a transmission running
        // read the next bit from the frame
        _state = _frame[_pos];
        if(_pos >= _frameSize) {
          _busy = false;
          _state = 0;
          _pos = 0;
        }
        _pos++;
      } else { // else transmit the idle pattern
        _state = 0;
      }
    }
    // Transmission
    if (!_manHalf) {
      digitalWrite(_pin, !_state);
    } else {
      digitalWrite(_pin, _state);
    }
    _manHalf = !_manHalf;
  } else {
    digitalWrite(_pin, HIGH);
  }
}

[...]

The corresponding, relevant lines in the header file are as follows:
[...]

class Transmitter
{
  public:
    Transmitter();

  public: //methods
    int sendData(LEDBitmap image);
    void transmitBit();
    [...]
    uint8_t* frameCheck;

  private: //members
    uint8_t _state;
    uint8_t* _frame;
    [...]

    int prepFrame(LEDBitmap image);
    uint8_t* buildBitFrame(uint8_t* frame, uint16_t size);
    [...]

};

[...]

The function transmitBit() is called every 1ms via a ISR.
Last but not least, here is my arduino sketch:
[...]

Transmitter transmitter;

[...]

int smallData[] = {1, 0, 0, 0,
                   0, 0, 1, 0,
                   0, 0, 0, 1,
                   0, 1, 0, 0};

LEDBitmap small(4, 4, smallData);

void setup() {
  Serial.begin(2000000);
  transmitter.setPin(4);
  transmitter.start();
  delay(200);
  pinMode(5, OUTPUT);
  digitalWrite(5, HIGH);
  transmitter.sendData(small);
  delay(1000);
  for(int a = 0; a < 88; a++) {
    Serial.println(transmitter.frameCheck[a]);
  }
}

The loop is currently empty.
Now onto the weird results I'm getting from printing checkFrame (which I have also already gotten when trying to print the full arrays inside my cpp). This is what it printed (already grouped in bytes):
1 0 1 0 0 1 0 1
1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0        // Up to here everything is fine.
0 0 0 0 0 2 149 0      // On the logic analyzer this line reads 0x00 as it should
221 5 15 0 2 149 0 1   // On the logic analyzer this line reads 0xff instead
1 222 0 98 2 149 8 218 // This line is irrelevant as it is only a buffer I added to see if the problem lies within my array not having enough space

Now onto my questions!
Do you have an idea what could cause this? Did I do the array assignment wrong? Could this just be an issue with the timing of the Serial.prints and my transmitter going off every 1ms? But why does my logic analyzer say that the last line is 0xff then? Do you have any idea how to fix this?
I'd be super glad if you responded as quickly as possible.
Thanks in advance!
EDIT: After increasing the initial value of a in my sketch to 64, I found out that the 8th byte is still 00000000 as it says on the logic analyzer. However, the checksum still was a mess. This did also not improve a lot after increasing it to 72. It then was 1 1 2 149 8 218 5 15. These last few values did also not change when I increased a again to 74.

_frame only holds the bits. It is a uint8_t array since that's the smallest possible data size.

The first for loop is dangerous: You might write data beyond the boundaries of your 10 byte buffer if image.getHeight() is big enough

uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t bitFrame[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; // <-- This frame is correct as well.
}

You are returning a pointer to a function-local array which was allocated on the stack. After the function exists the stack for that function gets de-allocated and the array becomes invalid.
It may be valid for a short time after the function exists, but as soon as new functions are called and variables are allocated on the stack, this gets overwritten.
See https://www.fayewilliams.com/2015/06/30/a-challenge-discussion-returning-pointers-to-local-variables/
In cases like these (especially with a constant maximum frame length), you should re-write your memory management to use statically allocated buffers within your class.
For example:
uint8_t* _frame;

to
#define SOME_MAX_SIZE 128
uint8_t _frame[SOME_MAX_SIZE];

And then re-write functions to write into these buffers instead of allocating new memory every time.
Dynamic memory allocation in general should be avoided at all costs on a microcontroller due to heap fragmentation.
If you really want to keep doing it you could also allocate a new frame of the required length and make sure to delete it after usage!
uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
  _frameSize = size*8;
  uint8_t* bitFrame = new uint8_t[_frameSize];
  int pos = 0;
    for (size_t byte = 0; byte < size; byte++) {
      for (size_t bit = 0; bit < 8; bit++) {
        bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
        pos++;
      }
    }

  return bitFrame; //return pointer to malloced array, okay now.
}

Thanks! I didn't think of that. That would explain the behavior! What'S the best way to fix this though?

@Lithimlin I've addressed that.

Hmm, I'm not quite sure when I could delete it, especially since bitFrame is defined within the local function. I mean, I can't just write delete [] bitFrame anywhere in my code, can I?

Or would a delete [] _frame inside the transmitBit() where I set _busy = false be enough?

The uint8_t* bitFrame = new uint8_t[_frameSize]; sure did the trick, but I still don'T know where to delete it again. Attempting to delete _frame inside transmitBit() resulted in the controller not doing anything anymore so I guess that's not how to do it.

@Lithimlin If you don't know when to delete the object that might indicate that the object needs to be always there and it made no sense to dynamically allocate it in the first place -- allocate it statically then. Or re-think the life-time of that object (maybe there is endTransmission() function that releases all memory?). There are multiple ways.

The way I understand it is the following:
Whenever the line uint8_t* bitFrame = new uint8_t[_frameSize]; is called, new memory gets allocated. This means if I call it 5 times without deleting in-between, I have space for 5 such arrays reserved and not usable. So wouldn't not deleting it quickly cause problems then?
Also I've already tried statically allocating them the way you suggested but I then get an error message telling me that there'S no definition on how to make a uint8_t[] from a uint8_t* (which is returned by my function)

@Lithimlin If you do a classMemberVariable = new uint8_t[someSize] 5 times while not deleting the pointer in between, you overwrite the old pointer reference to the allocated memory. Now you can never free that memory again because you don't have a pointer to it -- that's a memory leak. @static allocation: If you have a buffer inside as a class member, then you need to memcpy into it (or just write to it directly). If you upload a zip file with your project somwhere (googledrive, dropbox), I can have a look at it.

Let us continue this discussion in chat.


text:
Can not find the download Zip button in the GitHub Page
I want to download a zip file for the following code from the GitHub. I am pretty new in the GitHub. Can anyone help me how to download the Zip folder for the following code from the GitHub library? I need the folder named StopWatch.Zip to include in the Arduino Zero library.
 #ifndef StopWatch_h
#define StopWatch_h
//
//    FILE: StopWatch.h
//  AUTHOR: Rob Tillaart
// PURPOSE: Simple StopWatch library for Arduino
// HISTORY: See StopWatch.cpp
//     URL: http://playground.arduino.cc/Code/StopWatchClass
//
// Released to the public domain
//

#define STOPWATCH_LIB_VERSION "0.1.5"

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class StopWatch
{
public:
  enum State      { RESET, RUNNING, STOPPED };
  enum Resolution { MILLIS, MICROS, SECONDS };

  explicit StopWatch(const enum Resolution res = MILLIS);
  void start();
  void stop();
  void reset();

  uint32_t value();
  uint32_t elapsed()            { return value(); };

  bool isRunning()              { return _state == StopWatch::RUNNING; };
  enum State state()            { return _state; };
  enum Resolution resolution()  { return _res; };

private:
  enum State _state;
  enum Resolution _res;

  uint32_t _starttime;
  uint32_t _stoptime;

  uint32_t (*_gettime)(void);
  static uint32_t seconds()          { return millis() / 1000; };
};

#endif
// END OF FILE

In case, I have attached the link for this Code below.
Link for the StopWatch.h file

How is this an Arduino question? And this is surely nothing, that you couldn't have found out through googling.

go to https://github.com/RobTillaart/Arduino and click the "Clone or download" button.
The repository contains many small libraries, not only the StopWatch library.


text:
Arduino does not see data from nodemcu
I’m trying to send data from a NodeMCU to an Arduino nano.
If I try to send data with one second delay - all working fine.
But if I try to send without delay or with a delay less than one second, then arduino sees data but nothing not does.
Arduino nano sketch:
#include <Servo.h>

Servo servo1;

int servo = 6;
int engine = 5;

void setup() {
Serial.begin(9600);
analogWrite(servo, 67);
servo1.attach(8);
}

void loop() {
if (Serial.available()) {
String model = Serial.readStringUntil(':');
i

f (model.equals("engine")){
String value = Serial.readStringUntil('c');
int power = value.toInt();
analogWrite(engine, power);
}
if (model.equals("servo")){
String value_servo = Serial.readStringUntil('c');
int power_servo = value_servo.toInt();
servo1.write(power_servo);
}
}
}

NodeMCU sketch:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "my_wifi_ssid";
const char* password = "my_wifi_password";

ESP8266WebServer server(80);

void get_vars(){
if (server.argName(0) == "engine"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("engine:"+server.arg(0)+"c");
}
if (server.argName(0) == "servo"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("servo:"+server.arg(0)+"c");
}
}

void setup(void){
main_stuff();
}

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

void main_stuff(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

server.onNotFound(get_vars);

server.begin();
Serial.println("HTTP server started");

}

In the Arduino IDE, press "Ctrl" + "T" that will make your code easier to read.

What does this mean "But if i try to send without delay or delay < one second, then arduino sees data but nothing not does.", could you elaborate?

@MatsK, when the NodeMcu sends something to the Arduino - the built-in LED on it blinks

nothing not does is a double negative ... it means something does .... it is unclear what you mean by that statement

the newline characters from println (\r\n) stay in the serial input buffer and you read them with Serial.readStringUntil(':');. then the string is not "servo" but "\r\nservo"
if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them

And how to fix this?

Thank you very much! All work fine. I'am just change "Serial.println" to "Serial.print"


text:
Arduino Zero Compiling Issues for "Test-AnalogReadFast-SAM"
#include <Streaming.h>
#include "StopWatch.h"
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch Stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

Hi I have to run this code in the Arduino Zero. When I try to compile this code it throws the following error:
Error:
In file included from /Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:2:0:
/Users/RAJU/Documents/Arduino/libraries/Streaming/Streaming.h:102:15: warning: unused parameter 'arg' [-Wunused-parameter]
 inline Print &operator <<(Print &obj, _EndLineCode arg)

               ^
/Users/RAJU/Documents/Arduino/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino: In function 'void testAnalogRead()':
Test_AnalogReadFast_SAM:17: error: 'Stopwatch' does not name a type
 { static Stopwatch Stopwatch(micros);
          ^
Test_AnalogReadFast_SAM:20: error: 'stopwatch' was not declared in this scope
   stopwatch.start();
   ^
exit status 1
'Stopwatch' does not name a type

Any helps are greatly appreciated

what debugging have you done? ..... did you try anything before posting the question?

it should be static StopWatch stopwatch(MICROS);

The compiler doesn't know the type Stopwatch. You have a typo there. A short look into the header file (StopWatch.h) shows you, that it is StopWatch and not Stopwatch. You need a big W there.
Next time first try to investigate yourself. Obviously you didn't do anything before asking here. Next time try it and then, if you  cannot find the problem, then write in your question what you have tried.

I was able to compile the following program in my Arduino IDE for Arduino/Genuino Zero:
#include "StopWatch.h"

void setup() {
  static StopWatch Stopwatch(StopWatch::MICROS);
}

void loop() {
}

The StopWatch library comes from this Github page. It is the same, that you linked within your other language with the same code, so I assume, that you use it.
For future questions: It is better to directly provide links to all used libraries, that are not part of the Arduino IDE.

No, I tried many times. I tried StopWatch also. It throws the same error for StopWatch and Stopwatch.

For me it compiles if I also write MICROS instead of micros. If it doesn't for you, please write a minimal working example, that shows this error, with no other library included than StopWatch

Are you also using the Arduino Zero ?

Could you please send me the link for the StopWatch library that you have used? Thank you for your comment.

@RajuKC: Added the compilable code and the library link to the answer

Hi thank you so much for your reply. Whenever I ran this piece of code in my Arduino Zero Sketch folder, It says " 'MICROS' is not a member of 'StopWatch".

Are you sure you have the same library, as I linked in the answer? For this library MICROS is defined as a part of the enum Resolution

Hi, I used this library from the link "https://github.com/RobTillaart/Arduino/tree/master/libraries/StopWatch "

Mhh, maybe try this: static StopWatch Stopwatch(StopWatch::Resolution::MICROS); . this answer states, that this can also work, and it correctly compiles in my IDE. Also: What IDE version do you use?

Thank you very much for the suggestions. could you please send me the zip file of the exact StopWatch library that you have used? That might be more helpful.

Just follow the link to the Github page, that I wrote in the answer. Also this is the same link, that you already send in the comments. I think we can be sure, that we refer to the same library. The IDE version may be important, because they may use different compiler versions inside.

@RajuKC, the library comes with example code .... did you even bother to try one of the examples?

Thank you for the suggestions. I tried to run the example code in the Stopwatch library which also does not compile.

For the more information, I use the Arduino Zero 1.8.5 version


text:
what is the max frequency of external interrupt for esp8266 arduino?
i am using esp7 with AttachInterrupt() (Arduino) to count incremental encoder. I need to know what is the maximum frequency of pulses that esp7 can acquire.
also, need to know what frequency atmega328 can go with interrupt handling for an incremental encoder. my encoder 1000ppr.

This largely depends on what you are doing in the interrupt handler. Are you asking for the maximum frequency without any code in the ISR?

my encoder 1000ppr. ... this information is not relevant to the question.

On the 328 you can use the pulses as in input for timer2 (sync timer input). In that case the maximum frequency is one-fourth the frequency of what the 328 is running at. So 4MHz for the UNO.


text:
Understanding how to power objects with a relay (featherwing, feather huzzah)
I am trying to learn how to control a relay to power various household objects. I bought a power relay shield for an adafruit feather huzzah, and I have just set up the arduino blink sketch to provide conditional high / low to a control pin on the relay:
const int ledPin = 13;

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

void loop {
    digitalWrite(ledPin, LOW);
    delay(1000);
    digitalWrite(ledPin, HIGH);
    delay(2000);
}

If I connect a jumper from the signal pin hole on the board to the appropriate ledPin (13), I can hear the relay switching on and off. If I use a multimeter in continuity mode, it will register continuity at the appropriate times in the blink sketch (HIGH or LOW).
I might be confused on how the relay should be wired, but shouldn't attaching wires from two of the terminal blocks deliver power to something? If I use a multimeter on wires coming out of the blocks, I don't detect any current. I've tried powering a simple led, but I can't get it to light up. Here's my setup. Can anyone explain what I might be doing wrong? Does the LED need a separate power source apart from what's coming from the feather itself? (the feather is powered by a USB cable from my computer).
Thanks for any clarification anyone can provide.

BTW, here is a reference photo from Adafruit of how they have it wired.

the relay is just a switch .... it is like touching two wires together

why are you posting at multiple sites? https://electronics.stackexchange.com/questions/378824/powering-an-object-with-a-relay-has-continuity-but-it-doesnt-seem-to-be-delive

Please give actual wiring diagrams, not pictures of breadboards, its to hard to tell how yours is wired, and the picture from adafruit is useless

@mheavers crossposting is explicitly prohobited

@ChrisStratton - so do I delete this post? Stack exchange warns me that "deleting a post with answers deprives users of useful knowledge" - which I agree with.

A relay is just a switch, that is controlled via a magnet force from coil. The power line to the relay breakout board is just used to drive enough current through this coil, since often the 20mA of a normal digital output pin aren't enough for that.
Relays are for switching big loads, that should not have contact with the microcontrollers circuit. You don't want the 230V (or 110V, depending on where you live) to find their way to the microcontroller. Also most boards can only provide a very limited amount of current. Big loads mostly need a lot of current and you don't want this big current flowing through the tiny copper traces on the board. You have to use an extra power supply for these.
So have to connect the relay like a normal switch, in series with the load you want to control with it. Also keep in mind the difference between the normally open and normally closed output of the relay. Here is a schematic, to explain further, what circuit you need:

simulate this circuit – Schematic created using CircuitLab
You provide power for the coil of the relay from the two power lines of the ESP (3.3V and GND). The digital pin, that you use for switching is just a signal. It only has to provide a very minimal amount of current. The board itself has a driver circuit to activate the coil. Here I used a simple MOSFET, but I actually don't know, what driver circuit is really used on that board.
If enough current is flowing through the coil, the switch inside the relay changes from NC (normally closed/connected) pin to NO (normally open) pin, closing the electrical circuit, that provide the big load (here a light bulb) with current from an external power supply (like a wall outlet). The two circuits are NOT electrically connected, so you won't have to deal with potential high voltage and current on the ESP side.

And in your sketch you don't ever turn the LED off. I assume this is just an error from copy/paste.

@chrisi - thanks for the clarification - I did miss a line of code copying and pasting. But I still don't understand how the circuit should be wired. I've been searching for a fritzing diagram or circuit diagram, but I can't find something that simplifies this process.

@mheavers: I added a schematic and further explanations

I don't see a current limit resistor in the LED circuit, 270 to 470 Ohms, must have. Also, there is no power supply for the LED, the relay is just a short circuit across the LED.


text:
Error using SD card module: no matching function for call to
This code is just a test code to write a file to an SD card using an SD card module. When I run the code, I get this error message and I'm not sure what to do to fix the code: no matching function for call to'SDLib::SDClass::exists(SDLib::File&)'.
#include <SD.h>
#include <SPI.h>

int cs = 10;

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {

  }
  Serial.println("Initializing SD card...");
  Serial.println();

  pinMode(cs, OUTPUT);
  pinMode(SS, OUTPUT);
  if (!SD.begin(cs)) {
    Serial.println("SD did not initiliaze");
    while (1) ;
  }
  Serial.println("SD initialized.");

  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);

     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
  else{
    myTest = SD.open(myTestName, FILE_WRITE);
    myTest.println("Another Line of Data");
    myTest.flush();

  }

  Serial.println("Done Writing");

}

void loop()
{

}

The function is defined as
// Methods to determine if the requested file path exists.
boolean exists(char *filepath);

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90
You call it with a File object, not the filename. You probably mixed up the variable names:
File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  //[...]
  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);
     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
//..

Just exchange myTest for myTestName in the SD.exists() call.


text:
Where can I find the code for Arduino's "attachInterrupt"?
Where can I find the code for Arduino's attachInterrupt function?
A search on the Arduino's Github repo yielded nothing.
I suspect it might be a wrapper for some avr-libc function but nothing in the avr-libc docs stands out to me...

download a text editor like Notepad++  ..... you can then use it to search for text in folders (directories) ..... search for the text "attachInterrupt" in the arduino install directory .... it will find all files that contain that word   ..... get it here https://notepad-plus-plus.org/

It's in the core in WInterrupts.c
On my install it's at:
arduino-1.8.5/hardware/arduino/avr/cores/arduino/WInterrupts.c

Thank you! Never knew I could find these files in the install!

How could you compile them if they weren't there?

Online: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WInterrupts.c