The main problem I guess you are suffering from is the good old delay() blockage.

delay() is a terrible function and should be avoided at all costs.  Nothing at all can happen while you are running delay() - that means you can't be reading the state of your button - until all your delay() calls have finished.

If you want to queue the pressed of the button you will need to do three things:

You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
You will have to process any pending button presses ("while the count > 0") by triggering your output with the right timing without using delay(), which means using millis() and maintaining state information.


Control external device using Java Web Servlet -> Pi -> Arduino -> Device

You can use Ardulink. It's a java open source project of mine. It can control an Arduino boad. So you have just to write a servlet that call my library. That's it.

See this post to understand how install ardulink in a PI: http://www.ardulink.org/how-to-install-arduino-pc-link-on-raspberry-pi/

You can read a sample code that sends some messages to Arduino you can read this post:
http://www.ardulink.org/how-to-blink-a-led/

The most important statement is Link link = Link.getDefaultInstance();

Link is the Ardulink class you need to send (and receive) messages.


Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button

To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

In your code you detect the change only if serial is available, but you should do it in the loop.

The simple way to detect the change is doing this in every loop:

if (StateNow != PreviousState) {
  if (StateNow == LOW && PreviousState == HIGH) //button pushed
  {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    Serial.println("Turned off all LEDs");
  }
  PreviousState = StateNow;
}

I simplify your code and add some comments:

#define led1 10 //10th,
#define led2 11 //11th
#define led3 12 //12th
#define led4 13 //13th
#define ButtonA 9

int state;
int StateNow;
int PreviousState;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(ButtonA, INPUT_PULLUP);
  Serial.begin(9600);
  Serial.println("Enter ch a, b, c, or d:");
  PreviousState = digitalRead(ButtonA);
}

void loop() {
  //detect changes in button signal to turn off leds
  StateNow = digitalRead(ButtonA);
  if (StateNow != PreviousState) {
    if (StateNow == LOW && PreviousState == HIGH) //button pushed
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      Serial.println("Turned off all LEDs");
    }
    PreviousState = StateNow;
  }

  //check serial biffer to turn on leds
  if (Serial.available())
  {
    state = Serial.read();
    if (state == 'a' || state == 'A')
    {
      digitalWrite(led1, HIGH);
      Serial.println("Turned on led 1");
    }
    else if (state == 'b' || state == 'B')
    {
      digitalWrite(led2, HIGH);
      Serial.println("Turned on led 2");
    }
    else if (state == 'c' || state == 'C')
    {
      digitalWrite(led3, HIGH);
      Serial.println("Turned on led 3");
    }
    else if (state == 'd' || state == 'D')
    {
      digitalWrite(led4, HIGH);
      Serial.println("Turned on led 4");
    }
  }
}


arduino will not save data after receiving from serial communication

You are writing "62.1" but you are trying to read up until a \n, which you never send.
You need to ensure that you send the end-of-line character that you subsequently check for,
fwrite($port, "62.1\n");

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.
That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.
In doing so the sketch then runs fresh every time you open the serial port.
There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.
Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use SoftwareSerial and an external USB to UART adaptor instead of the Serial connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.


It seems you're using the same hardware Serial port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with Serial.print() and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making isValid() to always be false. You should instead create a SoftwareSerial instance attached to any 2 digital pins (maybe 2 and 3) like this:

SoftwareSerial ss(2, 3);

and in setup():

ss.begin(9600);  // use your module baud rate

Then at the top of loop(), use this instead:

while (ss.available() > 0)
    gps.encode(ss.read());

Get rid of the recursive call of loop() within loop() since it will cause your stack to rapidly overflow.

If you want data to only be sent when the location values are updated based on recent received data (but not necessarily changed, since you may still be at the same location), you should use if (gps.location.isUpdated()) instead.

Your call of dtostrf() is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:

dtostrf(gps.location.lat(), 10, 6, latitude);

You can also put this at the end of loop() to check if data is actually being received from the module and processed by the library:

if (millis() > 5000 && gps.charsProcessed() < 10)
  Serial.println(F("WARNING: No GPS data.  Check wiring."));
  while (1){ // infinite loop
    if (ss.available())
      Serial.print(ss.read());
  }
}

This site may provide additional details.


How safe is it to use my body as part of a circuit?

If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is 12V (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

I = V / R
I = 5 / 1500000 = 0.000003 A


I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib.
They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime.
I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time_t').


Existence of a non blocking and task yield framework for Arduino programming

I would recommend NilRTOS.
I like the fact that it's really minimal.
However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled).
But that will be the case regardless of the thread framework you choose.

You might want to try also femtoos.
I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.


(very new to C) I'm trying to use irsend with what I think is char* but it won't take it. How can I convert it to what it needs?

If you are sending HEX values like 0x1234abcd from the Pi to the Arduino to send those as an IR code you first have to interpret that string data as a hexadecimal number.
That's not as simple as just casting the string since, as @timemage says, all you're doing there is casting the address of the character array.
Instead you should use strtoul() to parse the string and give you the equivalent number to what it contains.
strtoul() can convert numbers in a number of different bases, and can even work automatically.  From the Linux man page:

SYNOPSIS
unsigned long int strtoul(const char *nptr, char **endptr, int base);

And later on:

If base is zero or 16, the  string  may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

That means it can automatically parse 0x1234abcd as a hexadecimal number, 12345678 as a decimal number, and 052714 as an octal number (it's important to remember that one so you don't accidentally add a leading zero to a decimal number and have it parsed wrong).
So knowing all that you can now:
uint32_t code = strtoul(buffer, NULL, 0);

and code will contain the contents of buffer represented as an actual numeric variable (assuming the content can be parsed as a number).


Check your baud rates. They appear to be different. That will cause problems.


Error taking address of temporary array when passing compound literal array

You can't with the Arduino. I am not quite sure why, but I think it may be because it's a Modified Harvard architecture machine.

You can better achieve what you want with variadic arguments, however:

void printConcatLine(int num, ...) {
    va_list ap;
    const char *s;

    va_start(ap, num);
    for (int i = 0; i < num; i++) {
        s = va_arg(ap, const char *);
        Serial.print(s);
    }
    va_end(ap);
    Serial.println();
}

void setup() {
    Serial.begin(115200);
    printConcatLine(3, "{", "255", "}");
}

void loop() {

}

The first argument is the number of arguments that follow, and all the rest are string constants.


Can an ATtiny print results to a console?

You don't have any output because you don't have a serial adapter connected to the device. The programmer you have is only for programming and does not support a UART serial connection.


Please read the documentation for the AccelStepper library.

Poll the motor and step it if a step is due, implementing
accelerations and decelerations to achieve the target position. You
must call this as frequently as possible, but at least once per
minimum step time interval, preferably in your main loop. Note that
each call to run() will make at most one step, and then only when a
step is due, based on the current speed and the time since the last
step.

source
You are only calling run once, after setting a new position.
Move stepper.run(); out of the if statement, the the end of the loop function.
      ...
      stepper.moveTo(nextStop*n);
    }
    stepper.run();
    n++;
}


Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes

No, you can't put the teensy bootloader on the UNO. The teensy has an ATMEGA32U4 and the UNO has an ATmega328.  The 32U4 has USB support in hardware the 328 does not.

The UNO does have a ATMEGA16U2 which does have USB in hardware like the 32U4 but it is programmed as a USB serial converter (to replace the FTDI chip used in earlier arduinos).

It might be possible to install a modified teensy bootloader on the 16U2 but that wouldn't help you because it is not connected to any of the I/O pins on the UNO.

In any case to install new firmware on the 16U2 you would need to buy something that can program the 16U2 via the ICSP and if you are going to buy something you might as well just buy a Leonardo or Teensy since they already support emulating a keyboard.

Now if you really wanted to spend the time it might be possible to write your own bootloader for both the 16U2 and the 328 on the UNO in such a way that they emulate a teensy or Leonardo but it won't be easy, and you would be limited by the smaller memory available in the 16U2.


How much voltage and current can a Arduino uno digital input sink?

You have 2 different questions here. First one can be answered by google search, it is literally the first result.

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of 150 200 mA.

And you should not apply more than 5V.

Regarding second question, Google can help again.

Vin is your 24V from controller, Vout is your Arduino digital 5V input. With that established, use voltage divider formula to calculate R1 and R2 values. I hope you can do that?
That being said, I am disappointed, because I feel like you have put 0 effort into researching this.


Ok, I have finally found the issue, and I am feeling very, very stupid.

I needed to calibrate the magnetometer with the figure-8 movement
I put a gigantic solid-metal 18650 Li-ion cell right next to the magnetometer chip...

EDIT: after replacing the 18650 with a polymer battery that is far away from the chip, things got a little better but both sensors in both devices still return garbage values.


Reversed Input Voltage Arduino Mega timeout communication with programmer error

Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.

In short: "It's dead, Jim!"


How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.

I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In

https://www.pjrc.com/store/teensylc.html

https://www.pjrc.com/teensy/index.html

The 3.1 and 3.6 are more powerful and more expensive at around $29

note: Read the index for which boards are 5v tolerant if that's what you need.


How can I hook up multiple MMA8451 accelerometers, (I2C protocol) using one Arduino Mega?

Brief explanation: When you talk to the slave device through I2C you start with (slave) device address. Then you send the message. It is like calling your colleague in an office with many other people. You say: "John", and when he is aware you continue with message, like "let's go for coffee".

This arrangement allows for adding up to 127 devices on one I2C bus. Each device must have different address (sorry, you cannot have two John's in the office, it will cause conflict). Generally two different type of devices will have different I2C addresses, but it may happen you need to use two (or more) of the same (like in your example). In this case, see below.

Many devices with I2C interface allows for address change. Using this facility you are able to communicate with many of the same devices through the same pair of cables.
You can check if your chosen accelerometer has possibility for address change: On picture below there is one with Address tab. When jumper is not fitted, you will get one address, when is fitted, the address of this device will be different, allowing of two of this accelerometers on one I2C bus. Unfortunately in this example there will be possibility of maximum of two of the same devices.

Of course there are devices with more than two possible addresses, you need to search for them.
And, yes, it is fine to use one Arduino to communicate with many I2C devices.

EDIT:
Looking after some of Adafruit accelerometers, I have found this page: https://learn.adafruit.com/i2c-addresses

And small off topic note: If you struggling on finding I2C with more than 2 addresses, check if it is easier to use SPI protocol. In this case you need (edited to correct bus lines names after user CrossRoads comment) MISO, MOSI, SCK and CS (chip select) wires. Chip select is individually connected to each slave device. This allows selecting particular device without addressing issue.


I need help setting up my Arduino Uno with the port

I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.


Serial input parallel output shift registers with arduino

unsigned char i;

digitalWrite(8,LOW);
for(i=0;i<=6;i++){
    if(x+i==6) shiftOut(11,12,LSBFIRST,dataArray[y]);
    else shiftOut(11,12,LSBFIRST,0);
    }
digitalWrite(8,HIGH);
delay(10);
digitalWrite(8,LOW);


The Arduino IDE doesn't ship with the source/assembly for a lot of the core functionality. It comes pre-compiled in object/library files.

However, you could download the source code for AVR Libc from this site:

http://www.nongnu.org/avr-libc

Obviously there's no guarantee that the files you download will exactly match what comes with the Arduino IDE, but it's useful if you're interested in how they're implemented.

When you've downloaded and extracted the source code, look in the libc/string folder. you should find assembly files called strcat.S and strcpy.S.

As jfpoilpret says in the comments, attempting to modify core library functions is generally not a good idea. They may be getting called by other parts of the core, so any changes you make could break something else.


Can Arduino accept HDMI input video stream, and output it without any modification to the video?

No.

HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing.  If you want something programmable to do that kind of thing you need an FPGA.


How to solve the white blocks on LCD keypad display?

The words you use to describe the parts of the display and which sketch you are using need to be more precise.

Regarding the part you linked to in your question, the dark blue part is the LCD (Liquid Crystal Display).  Not many buy just this part.  It is too hard to use.

Under it is a green board with the commonly found Hitachi LCD Controller.  This is what most people buy and call the LCD. Many Arduino sketches are written for the Hitachi LCD Controller. While you could connect this type of board directly to an Arduno, you would have to make a special cable which must follow the pin assignments in the particular sketch you are using!

Finally, the darker board beneath the green board appears to be an Arduino shield.  Normally Arduino shields adapt what ever circuit happens to be upon the shield to the Arduino Uno pins and form-factor.  However, again, you mush use a sketch which which follow the pin assignments for the particular shield!

Armed with this knowledge, you should be using/looking-for a sketch specific to your Arduino shield. I suspect you are using the wrong sketch and this is resulting in "white blocks" on your LCD display.

Other considerations:

It is possible your contrast in incorrectly set.  Identify if this control is available on the shield you are using and consider adjusting it.
Is the shield plugged in correctly?  Check to make sure all the pins are connected to the Arduino.  Most shields are designed specifically for the Arduino Uno form factor.
If you are still having problems, consider buying everything (the Arduino Uno and the LCD shield) from one specific well known vendor which can supply support through direct contact or forums.  Usually a good vendor will provide support especially if they provide all parts of a project.

Other approaches:

You should find a sketch which works with your LCD & Buttons Arduino shield.  However, as you have figured out the paths between the Arduino and the Hitachi like LCD Module you might try using the LiquidCrystal Library.  When this library is instantiated, the pins of the Arduino which are to control the Hitachi like LCD module are passed as arguments.  Using the information in the question, it is likely the instantiation should look similar to this:

LiquidCrystal(12, 10, 5, d5, 4, 3)

...Note, you are missing "d5" in your question.  So the above is likely not correct.  Also, from your description, the Arduino appears to control contrast ("V0" pin) for this shield.  As the LiquidCrystal library does not appear to support this, you may need to create additional code to control contrast.


Microcontrollers with built in HID support

The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).

The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.

You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like in this project


Should long wires be kept separated from each other, to reduce interference?

A benefit of using CAT-5 is that the pairs are twisted.  You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used.  Telephone wire, however, can be a completely different story.  You may find some that is twisted pair, but most if it is simply flat cable.  Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it.  This is very high loss and very vulnerable to RFI.


How to use analogWrite() on multiple pins at the same time?

You have your parameters the wrong way round:

analogWrite(2, 100);
analogWrite(6, 200);

However: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with ~ - they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.


Can I integrate Arduino in a CI/CD setup?

There are different approaches around. I can only point you to some of them:

GitLab CI approach A
GitLab CI approach B
Your specific solution: To build pipelines for Arduino (although its Azure) but you can use this technique on Linux with Jenkins

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes


I ran your sketch and this is the output signal:

analogWrite produce a square wave.

As Majenko said, you have to add a low pass filter to get that sine wave.


Is there the only wire from Arduino to the Base of Transistor?

Basically you need something like this:

If you reverse the transistor (E and C), builtin protection diode will be in forward direction, so electro magnet is on.

If you have only one wire to the base, it cannot work as you need current to the base.

If you don't have R1 into the base (about 500R-1K), it'll burn your output eventually. (not if you don't have common ground)

If you have electro magnet between ground and Emitter, you'll have negative current feedback and about 4.2V on L1 tops as there must be some current into the base.


It's possible that time.sleep is causing a latching issue. You should instead use pymata-aio's sleep function:

uno.sleep(0.001)

The documentation for it can be found here: http://htmlpreview.github.io/?https://github.com/MrYsLab/pymata-aio/blob/master/documentation/html/pymata_aio.html#module-pymata_aio.pymata3

You could also try a different pin and see if you still have the issue?


Can I use an IR distance sensor in rain?

According to the data sheet for this device, located at Adafruit's web site, the frequency used is 870nm. If you required specific attenuation figures, that might be useful information.

Another web site suggests that thermal IR camera imaging systems (which use a different frequency IR) are attenuated by rain. Some of the IR energy is lost by absorption and some by reflection. I was hesitant to suggest that as the answer due to the different frequencies involved.

Digikey has a document covering wide use of IR sensing. Listed in the document:

The disadvantages of IR technology are:

Line of sight: transmitters and receivers must be almost directly
aligned
Blocked by common materials: people, walls, plants, and other objects can block transmission
Short range: performance drops off with longer distances
Light and weather sensitive: direct sunlight, rain, fog, dust, and pollution can affect transmission
Speed: data rate transmission is lower than typical wired and RF transmission

Even though data transmission is not your objective, the considerations apply. A wet surface over which your sensor passes will have the signal attenuated and may also be slightly diffracted.

I found no direct reference to the magnitude of the attenuation. If your sensor is protected from water intrusion and the surface is only slightly wet, you may have minimal problems reading the distance. If the rainfall is at the level of a frog-strangler, there could be sufficient water to eliminate useful readings.

Another search resulted in a similar question on the physics stack exhange, which led to a more comprehensive answer:

There is another image on the same page, but both show that at the 870nm frequency, there is lower attenuation than much of the IR spectrum, particularly above 3000nm. The above linked document suggests that the affect of rain (water) is low at near-infrared (970-1940nm) but that's still higher than the device's 870nm figure.

For your objective, shielding the surface from rain (umbrella) or clearing the surface of standing water seems to be the best options. If those are impractical, one would have to experiment to determine how much water flow can be tolerated before the signal is lost or attenuated beyond reception limits.


Following on from user1637451 the following sequence has always worked for me:

Before download, pull both GPIO0 and RST to ground.
Release the pull down on RST, but keep GPIO0 low.
When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.

As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.


RGB Led strip pot control burned my arduino?

First, as Majenko said, you need resistors between the arduino output pins and the transistor bases. Start at something like 330 Ohm.
Second, what is the value of the potentiometers? If it is too low you would be drawing too much current from the 5V pin to the ground.
Third, you should power the arduino with at least 7V, assuming you power it through the Vin pin or the power jack. 6V is considered too low.
I assume the pins connected to the potentiometers are initialised as inputs. Otherwise, it would be possible to burn your arduino by having them source/sink too much current (i.e. by turning the potentiometers to one end or the other).


The way I see it, the state should go back to IdleState if the button is not pressed. Just putting the switch-case inside the if-statement will result in the motor continue rotating the way it was rotating when the button is released.
if (button1State == LOW ) {
  State = IdleState;
  counter=2000;
}
else if(button1State==HIGH && State==IdleState ) {
  counter = 0;
}

switch(State) {
  ...

Depending on what it is you want to do, you might want to add another state (say StoppedState), where the motors are halted, just like IdleState, but you don't get a state change if counter<2000. Then you don't have to change the counter variable.
if (button1State == LOW ) {
  State = StoppedState;
}
else if(button1State==HIGH && State==StoppedState ) {
  State = IdleState;
}

switch(State) {
  case StoppedState:
    halt ();
    break;
  case IdleState:
    ...

PS please indent the if statements inside you cases.


Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)


Write a condition to execute 2 switch-case functions?

There is something incoherent in your code. It is structured as a finite
state machine, and yet you are using delay() within it. In this kind of
scenario, the whole purpose of a state machine is to avoid using
delay(), so that your program never blocks. If your program happens to
not have anything better to do than delaying, then you can forgo the
state machine and write much simpler code. For example:

void warn_and_flash(byte pin)
{
    // Flash the "warning" LED.
    digitalWrite(7, HIGH);
    delay(5000);
    digitalWrite(7, LOW);

    // Flash the requested LED.
    digitalWrite(pin, HIGH);
    delay(2000);
    digitalWrite(pin, LOW);
}

void loop()
{
    if (voltageA0 > 1.0) warn_and_flash(8);
    if (voltageA1 < 2.0) warn_and_flash(9);
    if (voltageA2 > 3.5) warn_and_flash(10);
}


This is called (by me, anyway) "method chaining".

It's nothing special, really.  ArduinoOTA is just an instance of the class ArduinoOTAClass.

Each method of that class does what it needs to do, then returns a reference to the object that the method is within.  Which means that you can then call a method on that returned reference ... and so on.

All the rest of it is "lambda" functions - that is, functions that are embedded within the parameters of the functions being called.

The basic result is something like:

A.foo().bar().baz();

Where A.foo() returns A. A.bar() returns A. A.baz() returns A.

You can do the same with:

A.foo();
A.bar();
A.baz();


I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
Queue

I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.

2 methods are implemented to interact with the queue, push() & pull().
I'll probably add a peek() later on if needed.

I also noticed this other FIFO only queue lib in the library manager when I commited mine: MD_CirQueue

Hope this can help!


Control arduino with keybaord via computer

The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.

Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.

There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.

Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.


Set up a motion sensor to turn on lights and record how long the lights are on

I would consider placing a light sensor close to one of the lights to signal when the lights are on. Placement is critical as you do not want a signal when the lamp is off. I am assuming they are permanent light fixtures and you are not allowed to tamper with the wiring.  Record the elapsed time when they are on.  Note the start time and then subtract that from the current time based on your watch. For elapsed time and subtract the ontime from that. With the sensor you can also record each time the light is turned on etc. That would all be in your software.


Sketch stops printing after writing a few times

What you see is undefined behavior. You define your buffer to have a length of 50 bytes:

  char buffer[50];

This is too short for most of the strings you want copy into it and you will thus overwrite other variables.

The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at http://linux.dd.com.au/wiki/Arduino_Static_Strings for hints how to avoid wasting RAM for the buffer.


There is two kinds of buzzers - active and passive

Passive buzzer means they can be operated by applying  just logic high to + and low to ground.

Digitalwrite function will do this job

Active buzzers needs pulses to make sound. Sound produced depends on the frequency.  Your buzzer might be a passive one. You can make a symphony by applying different frequencies..

'tone' function will help you for this


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


Neopixel Painter - Need to change few lines. Not sure where to start

I think you need something like this.

  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line

    if(++block >= nBlocks) {                   // Past last block?
      block = 0;                               // Loop back to start
    }

    if(digitalRead(NEXT_PIN_OR_SOMETHING) == LOW) {       // Next button pressed
      break; // Break out of for-loop
    }

    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }


If you upload to a SAMD board like the MKR boards or the Nano 33 IoT with Nano 33 BLE selected in Tools menu of Arduino IDE, the upload is executed and deletes the bootloader of the SAMD MCU.

The problem is that bossac uploader doesn't check the chip, because it was developed only for the SAMD chips, but Arduino created a bootloader for the Nano 33 BLE nRF52 MCU to use the SAMD bossac uploader.

The SAMD boards use the native USB support of the MCU, so without a bootloader or good sketch running the USB doesn't work.

You have to restore the bootloader on Nano 33 IoT. It is done over the SWD pads on the bottom side of the board. You can use a SWD programmer or other Arduino board with the Adafruit DAP library.

You can use your Nano 33 BLE or some other board and a SD card with Adafruit DAP library as programmer.

I had this problem with MKR Zero and I used a LPC-Link2 programmer to burn the bootloader. Once before I lost the bootloader for other reason and back then I didn't have the programmer so I used the Adafruit DAP library with an Arduino M0.


Yes.  Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.

You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.

If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent.  If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done.  A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.


I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port.  That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character.  As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.

Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.


Achieving nanosecond accuracy with MKR Vidor 4000

No. You can't.
To achieve 1ns precision you need a 1GHz clock. That can't happen.  The MKR Vidor 4000 uses an FPGA with an "A7" speed grade. That means that (according to Table 20 here) you can't run at any more than 402Mhz internally (200MHz is all Arduino are rating it for).
Not even half.
Around 5ns precision would be the absolute maximum precision you could get if you stick to the Arduino clock specs.


Which relay module to buy and what is the difference between 1 channel and 2 channel relay boards

Yes, you can use those. You have to watch a few things:

Input voltage: 5V, perfect for Arduino
Output voltage: 220 V, perfect for 220V AC
Output amperage: 10A, what you control should use max 10 A, and I would use max 5A, and also consider switching on current into account. However, 10A is a lot of current.

The difference between 1 and 2 channels relay boards, is just that there are either 1 or 2 of them, meaning you can control 1 or 2 motors independently from each other.


Possible hardware solution:

Consider using 2 battery packs.  One connected to the Arduino and the other connected to the motor drive board.  Remember to connect the grounds of the 2 battery packs together.

Possible software solution:

Software is often over looked when solving what appears to be a hardware issue.  Consider introducing a short pause between motor direction changes.  It may be that the power required to reverse the direction of a motor exceeds the capacity of the battery pack.  Likely it will take less power to first stop the motor, pause then start the motor in the opposite direction.


In Android, I used this UUID to connect to HC-06,

  socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

  inputStream = socket.getInputStream();
  outputStream = socket.getOutputStream();

You can use this UUID in your Android code, But over iOS, I think the Bluetooth is really a completely different hardware specs.

Hope I helped


The LED on pin 13 is used by the optiboot loader (the one used on UNO):

at Arduino boot time (the LED blinks a few times)
when uploading a sketch to Arduino

I haven't checked other bootloaders, they may provide the same behavior as the optiboot.

For optiboot, there are optional defines (at compile time) to modify this behavior:

LED_START_FLASHES defines the number of flashes of pin 13 LED at boot time (can be set to 0)
LED_DATA_FLASH will use pin 13 LED during sketch upload if defined at compile-time

These defines are explained in hardware/arduino/bootloaders/optiboot/optiboot.c from within your Arduino IDE install directory.

If you want to change these, you will have to recompile the optiboot loader first and then burn it to your Arduino through an ISP programmer.

I guess one other reason for the LED on pin 13 was to simplify the demonstration of the "Hello World" sketch for Arduino, namely the Blink sketch, without the need for any extra component.


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


The typedef is no longer needed, using the 'struct' with a name declares the type.

// Arduino Uno

struct buttons
{
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
};

// Declare the functions here, or use prototyping
void func1();
void func2();

buttons test[] =
{
  { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
  { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
};

void setup()
{
  Serial.begin(9600);
  Serial.println("Calling the functions:");

  test[0].fn();
  test[1].fn();
}

void loop()
{
}

void func1()
{
  Serial.println("func1");
}

void func2()
{
  Serial.println("func2");
}


Switch Case Return , Return not printing

You misunderstand the use of return.  The loop function is declared void.  That means it doesn't return anything.  If you simply remove that return statement completely then your code will do what you want.

The return stops the loop.  It throws away the value since the loop is defined as returning void, and code execution never reaches the print statement.  Writing anything in a function after a return statement is useless.


Discrete H-Bridge very low current output

Design 1 wouldn't be my first thought on how to do this either! The transistors aren't a great choice, but are cheap & common.

The layout here is more conventional, and you can physically link 1-2, & 3-4 to connect to your arduino without the risk of short circuits.

I suspect your code may be setting both lines high together - the only advantage I can see to the posted circuit is that this does not necessarily cause smoke (but may well do as you describe). This is why posting the code is recommended!


How to Read ADC value without Common GND ? (Possible or not !)

The solution is to always use at least 2 electrodes. You need 1 electrode, that you connect to ground. You can put this electrode to somewhere neutral (this instructable suggest connecting it to your leg, but I don't know, if that position is really good).

An ADC measures voltage and voltage is the difference in potential between 2 points, so to measure voltage you by definition need 2 points/connections.

Note: The voltages from the EEG electrodes are normally very low, so that they completely vanish in the noise. To really get something useful, you need to amplify the signal. I think there are many tutorials out there, that explain how to do this.


Move a servo slowly between 2 positions based on input

Lacking information about the context of the servo action (ie, what needs to happen at the same time), I'll assume your paradigm uses a loop() function that executes fairly rapidly, and from time to time invokes any necessary actions.

Servo angles can be measured in degrees (typically 0 to 180) or microseconds (typically 1000 to 2000, corresponding to 0° to 180°).  The servo library will accept numbers in either range, and act according to which range the numbers are in.  Note that representing servo angles in microseconds instead of degrees gives about 5.55 times better resolution.  The method outlined below doesn't care which you use.

Also assume the two servo angles mentioned in the question are A and B, with the servo at A if the input pin is low for a long time; and that the desired rate of swing is ±U units of angle every S milliseconds.  Let P = current servo position; T = millis() value at most recent step, initially 0; and V = previous value of input pin.

In each pass through loop():

• Test the input pin.  If it isn't equal to V, toggle V and take a step.  (See below.).
• If  millis()-T > S, take a step.  (See below.)
• Do any other brief per-loop actions

To take a step:
• Add (2*(V>0)-1) * U to P.  The expression (V>0) equals 1 or 0, so (2*(V>0)-1) is 1 if V is true, and -1 if V is false.
• If (V) and P > B, set P = B
• If (!V) and P < A, set P = A
• Servo to position P
• Set T = millis()

Edit: You should create meaningful variable or constant names to represent the quantities A, B, P, S, T, U, V.  Note that S and T should be declared as constants; and if A, B won't change, make them constants also.  State-maintaining quantities P and T should be declared via file-scope variables or globals (outside loop()) or with static allocation (inside loop()), so that their values are maintained as main() repeatedly calls loop().


Lighting LED Strip via HC-06 Bluetooth Module

Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().

int currentmode ;
int previousmode ;

void loop()
{
   previousmode = currentmode ;
   currentmode = getnewmode(currentmode) ;
   if (currentmode != previousmode)
      initmode(currentmode) ;  // turn new mode on e.g. change LED color
   nextstep(currentmode) ;     // if current mode is dynamic, make change
   delay(DELAY_INTERVAL) ;
}

int getnewmode(oldmode)
{
   if (!serialpending()) // no serial input
      return oldmode ;
   return parseinput() ;
}


Why is this extremely simple code not working?

The problem is:
for (int x = 0; x > 10; x++) {

That can be rewritten, in pseudo code, as:

X is zero
While X is greater than 10:

Increment X

You see the problem? X is zero. It's not greater than 10, so it never increments.
I assume you actually wanted:
for (int x = 0; x < 10; x++) {

Also be aware that your for loop will be run over and over again, so you will never see it finish.  You should add
Serial.println("Loop done");

at the end so you know it's finished.


Question about include statements and details in Arduino.h file from core library

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the -I command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

  One last question, how can there be an Arduino.h without an Arduino.c?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.


send serial monitor to server and save data in hdd

You could look and see if there was any data logging libraries already written or you would need to develop a function that wrote to a file held on an SD card.  There are plenty of SD libraries.

If you mean you have a computer connected to the serial connection from the ATMega then there are probably logging programs out there, some terminal monitors save what they receive.


analogRead seems to freeze some seconds the program

analogRead() is fine, it takes only about 110 µs, but there are
several other issues with your code that you should fix:

Any variable that is shared between interrupt code and normal code
should be declared volatile in order to prevent the compiler to do
some unsafe optimizations.
Any such variable that is more than one byte in size should be
accessed from the main program with interrupts disabled.
You should take care of not writing into databits[] past the end of
the array.
Counting loop iterations is a very bad way of measuring elapsed time,
as the counting speed will change whenever you change your loop code.
Use micros() instead.

There is also an issue with how you use flagDone. You set it to 1,
then you call analogRead(), MicroViewSlider::setValue() and
uView.display(), then you read it back. What if your ISR has set it
back to 0 in the meantime? I suspect this is the main cause of the
problem you see.

I suggest you use flagDone to inhibit the ISRs: the main loop sets it
to true to tell the ISRs “Let's say we are done with this card. Please
do not touch anything while I process the already received information.”
And later it sets it to false meaning “You can proceed reading bits
now.”

Given the above considerations, I would try something along these lines:

volatile bool flagDone;     // if we are done, pause the reading
volatile uint8_t bitCount;  // number of bits received so far
volatile uint32_t rxTime;   // last time we got a bit

// Interrupt that happens when INTO goes low (0 bit).
void ISR_INT0()
{
    if (!flagDone && bitCount < MAX_BITS) {
        rxTime = micros();
        databits[bitCount++] = 0;
    }
}

// Same thing, but writes 1 instead of 0 into databits[].
void ISR_INT0() { ... }

void loop()
{
    // Safely read rxTime.
    noInterrupts();
    uint32_t rxTimeCopy = rxTime;
    interrupts();

    if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
        // Assume we are done reading this card.
        flagDone = true;

        // Do whatever with databits[].
        // ...

        // Get ready for the next card.
        bitCount = 0;
        flagDone = false;  // do this last: it re-enables the ISR
    }
}


Are my stepper motors being burnt out? What is the issue here?

So the problem was that somehow the potentiometer had reset its own vref output. I couldn't adjust it after it did this. I replaced both drivers and it works like a charm now.


Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written.  However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.

Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on.  (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.)  The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.

//  jw - 8 Mar 2016 - Program for buttons demo
// Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
enum { nSwitches=5 };
byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
unsigned long startTime;
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
  // Note, this code assumes one side of button goes to Ground
  // and other side to a digital pin with its input pullup turned on
    pinMode(buttonPins[i], INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Program begins");
}
//--------------------------------------------------------
void doButton(byte b) {
  char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
  if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
    // The b'th button has freshly turned on.
    unsigned long now = millis();
    if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
      return;
    buttonBusy[b] = 1;
    if (b==0) startTime = now;  // Button A resets timer
    Serial.print("Button ");
    Serial.print(blabels[b]);
    Serial.print(" at time ");
    Serial.println(now-startTime);
    if (b==nSwitches-1) {   // Last Button ends timing, restarts cycle
      for (byte k=0; k<nSwitches; ++k)
        buttonBusy[b] = 0;  // Clear all the busy-flags
    }
  }
}
//--------------------------------------------------------
void loop() {
  for (int b=0; b<nSwitches; ++b)
    doButton(b);
}

Edit: Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.

Before explaining that, let's look at why the above code should work.  Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds.  Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break.  When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on.  When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off.  And finally, assume each button press is long enough that at least one digitalRead() happens while contacts are closed.

Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed.  Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons.  So we can ignore bounce.

On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.

Here's a method worth considering if you want to implement trigger-on-release:
 • First, add a delay(1) call, in loop().  This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute buttonBusy[b] = 40 to start (or restart) a 40-ms timeout.  That is, while a button is held down, we keep setting its timeout to 40.  (40 ms may be overly conservative.  20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
 • if buttonBusy[b] is zero, do nothing.
 • if buttonBusy[b] > 0, then decrement buttonBusy[b] and test if it now is equal to 1.  When it's equal to 1, regard b as released, so do its action.


The error message is telling you that avrdude failed to open the device and read the modem status (basically the information about whether a device is present and ready on a serial line). The most likely causes of this are:

Using the wrong serial port (Tools > Port in the Arduino IDE).
The IDE not recognizing the board.
Using a power only USB cable.

The Arduino IDE seems to remember the device that your board was last connected through, but on some Unix flavored OSes the device name depends, in part, on method of connection – which port, hub or no hub, etc. So if you change the board or the port you plug it into, the name changes.

So, the very first thing to do is to look under  Tools > Port in the Arduino IDE to see if there is another device present. Also confirm that you're using a USB cable with data wires. There are "power only" USB cables…

Failing that, check to see if the OS sees the board. On OS X you would go to the Apple menu and choose About this Mac and then look at at the System Report to see what devices have been detected on your USB busses. I'd be surprised if there wasn't something similar on Linux (and Windows too for that matter). If you're comfortable on the command line you could look in /dev for devices with similar names.

If the board is present, but not seen by the Arduino IDE, try restarting the IDE and/or plugging and unplugging the USB cable. Sometimes it helps to plug the cable into a different port.


Voltage on analog pin arduino when arduino turned off

All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

simulate this circuit – Schematic created using CircuitLab

The internals of the ATMega chip can be visualised for this purpose as a small resistor:

simulate this circuit

If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

simulate this circuit

That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.

It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.


Increase IR transmitter directivity and range

The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).

So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.

But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.

The back side (flat one) should not be sensitive.

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).

But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".

You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).

In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.

First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).

But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

TLDR: I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.

Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.


Software:  Wire should be fine.  Of course, you usually will want libraries for each device.  This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly.  Here is the DATASHEET

I2C Hardware:  On the Arduino Uno, SDA is A4 and SCL is A5.

One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.

The reason for this is that the I2C bus is active-low.   It signals by pulling the pins low in sequence to communicate.

If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

It might be easier for you to use a different I2C ADC such as the ADS1115.

Here is a generic search that shows the module:

https://smile.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=i2c+adc

Here is a generic search which shows the software side:

https://www.google.com/search?q=arduino+ads1115+ADC+library+download


Can a shift register be used to extend the Arduino pins when an ethernet shield is mounted on the Arduino?

You can control a shift register with shiftOut or bit-banged SPI.

My page about SPI has a small library that does bit-banged SPI.

It is also possible to control a shift register using the same pins (MOSI/MISO/SCK) that the Ethernet interface uses, as long as you use a different SS (slave select) pin for your shift register. This may not be practical if the Ethernet card is active all the time. It is probably easier to do the bit-banged SPI or use shiftOut.


I need help creating a code that moves a DC motor CW or CCW based off of 2 different buttons

To formulate the comments into an answer:
In principle it is of course possible to put an encoder onto a DC motor shaft and then drive the motor, until you reach the desired position. But you won't get good precision or accuracy with this. You wrote

till the encoder reaches +10 from where it was at

Since most encoders have more than 10 tics per full rotation (you didn't specifiy how much yours has), this can mean  rotating only a fraction of a full rotation. Let's assume, that the encoder has 40 tics per full rotation. With 10 tics you have a quarter rotation. It seems you want precision in the range of about 1 tic.
DC motors are made for spinning relatively fast. They don't give you control over the position with steps. They mostly have very few coil/magnet combinations (for example just 2 coils, which are switched internally). Thus you have just an inert motor shaft, which is driven by the motor. It will need time to accelerate and to decelerate. With most motors, you may even get a half or full rotation, when you wanted only a quarter rotation (the 10 tics). Calculating the correct timings to get it any better will be not easy for relatively small reward. DC motors are not made for rotations below a small number of full rotations.
You could tackle that problem by using a geared DC motor. The shaft after the gears will run slower and thus have the explained problem not so badly. Then you have to live with the smaller speed.
Or you could go a more proper way and just use a stepper motor, which is made for small steps in the range of sub-full-rotation. It is a bit more difficult to drive (also depending on the driver circuit), but it gives you the position control, that you want. And to rotate continuously: A continuous rotation on a stepper motor is nothing else but step after step taken in fast succession (much like running is a fast succession of steps with your feet).

Note: The stepper motor does not have a feedback like an encoder on it. The motor driver will just drive the coils to step the motor. If the motor is stalled or if it is overloaded, you might loose some steps (meaning that the coils are driven for the steps, but the motor doesn't actually move). You could sense that with an additional encoder on the motor shaft. But in most cases that is not necessary. If you just make sure, that the motor is not overloaded at any time, you will be fine. Or you might not worry about some steps being lost sometimes, if the overall precision is good enough. That is your decision.


How to connect L298N motor driver to 5v input supply?

Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the L298 datasheet when listing the L298N I will assume they are reasonably equivalent.

I will assume that the "12V-35V input pin" is the V_S pin, despite that label. There are only two supply pins on the L298 with the following electrical characteristics:

V_S, Supply Voltage, pin 4, Operative Condition V_IH + 2.546V (max.: 46V)
V_SS, Logic Supply Voltage, pin 9, typical 5V (min.: 4.5V, max.: 7V)

with

V_IH, Input High Voltage, ranging from 2.3V to V_SS

Which would explain that the circuit works at 7.2V under the assumption that the logic inputs (enable A and B as well as inputs 1 through 4) are at close to 5V high levels. And here's the trick that might make it work: as noted V_S (the supply voltage) needs to be at a level of V_IH + 2.546V while V_IH could be as low as 2.3V and 2.3V + 2.546V < 5V. So driving the L298's logic inputs with a lower voltage for logic 1, i.e. closer to 2.3V high levels, could help.

Why is this? (source):

  [..] The actual restriction is that the motor supply be somewhat greater than the logic "1" input, but that need not match the logic supply. [..]

A warning though:

this circuit is now operating at the fringes, one might call it shady at best, intolerable at worst
saturation voltage is related to output current and other parameters, e.g. temperature, so this might work now under certain conditions and fails horribly another day

Therefore better bets are:

use a higher supply voltage
ditch the L298 and its high voltage drop Darlingtons and use a MOSFET H-bridge motor driver, such as the TB6612FNG, see also
ditch the L298 and use single bipolar transistors, depending on the output current

Other things to check:

Make sure V_SS is connected to the logic supply voltage (see AnT's comment). Make sure GND of the Arduino's power supply is connected to the L298's GND.


Arduino Leonardo - Setting up bluetooth - AT command from terminal does not return anything

The issue is fixed.
Note: This is the version includes Serial1 rather than SoftwareSerial. The rest is the same.
Serial.read()

Returns the first byte of incoming serial data available.

So, when I send AT command from terminal, it does send "A" and then "T" rather than "AT" as a string which Bluetooth expects as stated in the product's documentation:

AT Command format: Uppercase AT command format. string format, without any other symbol. (e.g. \r or \n).

Hence, I have added the following function:
String SerialString() {   // Function to generate string from chars sent via Serial Monitor

  String inputString = "";  // to hold the string

  while (Serial.available()) {

    char inputChar = (char)Serial.read(); // get the new byte:
    inputString += inputChar;             // add it to the inputString:
    }

    return inputString;     // returns completed string
}

Then inside void loop():
String WholeCommand = "";
if(Serial.available() > 0){
    WholeCommand = SerialString();
    Serial1.print(WholeCommand);
  }

Now, when I send AT from Serial Monitor, I can get OK from Bluetooth.


Use the stepper motor library with the A4988 driver?

That library is not compatible with the A4988. It is intended to do the same job that the A4988 does. You provide a step direction and an instruction to step, and it does the stepping for you.
To use the A4988 you just set a pin HIGH or LOW for the direction, then toggle another pin to make it step. You don't really need a library for that.
However if you do want to abstract it with a library and add lots of cool extra features then you should look at AccelStepper which supports 2-wire drivers like the A4988.


someVariable = { somethingThatLooksLikeAFunction }; possible?

You can do it with a lambda function, though the syntax is somewhat cryptic:

int someThing = [](int y, int z, int a, int b){
    for (int _x = 0; _x < y; _x++) {
        z++;
    }
    return (z > y) ? a : b;
}(100, 0, 10, 20);

In that you are defining a lamda function [] with four parameters, y, z, a and b. Then calling that function with four numbers (100, 0, 10, 20) and assigning the return value to someThing.

It's the same as writing a normal function but there's a lot more brackets around.


Plug/socket between thermocouple wires and the amplifier

I do not know the accuracy that you will require in your temperature measurements.

Your idea of using copper wire and connector sockets is reasonably ok as long as you are aware of the following :

Where you make a connection from thermocouple wire to copper, that creates another thermocouple in itself. This isn't a great problem since the temperature of the "undesired" thermocouple is likely to be at room temperature (constant?)

No matter what you do, you always end up with undesired thermocouples (example when you connect your thermocouple directly to your circuit board copper, darn it.)

Thermocouple Selection and use is a page you can go to for more information.  Especially the Cold junction compensation (CJC) section.

EDIT added : You should twist your extention leads together to reduce electrical noise from the environment. Twist each pair, do not twist the bundle all together.


Switching external power supply to 5V cooling fan with an Arduino and 2N2222 transistor

To fully turn the transistor on you should give the base somewhere around 1/10 to 1/20 of the collector current. If you read the datasheet for the PN2222 (a highly recommended activity) you will see that Vce(sat) is specified with Ic/Ib = 10.

Now, the Microchip ATMega328 MCU chip in many (but not all) Arduinos is capable of sourcing 10mA or 15mA with minimal drop (assuming a 5V supply), again this information is available in the MCU datasheet (Figure 31-71 on page 355).

So it appears you are using an "Arduino" with some other MCU. In which case you can either use another transistor to boost the current or substitute a logic-level MOSFET.


So here are your needs:

WiFi, which uses pins 4, 10, 11, 12, 13. I know you said that you don't need pin 4 since no SD, but because that pin switches on/off the SD card, if you use it at all. Note: As Connor Wolf points out, it's not really relevant when there's no SD card. If you're facing problems with the Ethernet shield using the LCD additionally, you might have to reroute pin 4.
LCD, which uses pins 4, 5, 6, 7, 8, 9. The standard Arduino LCD library can use any pins, but your shield is hard wired to use those. As mentioned before, you can reroute them if you want to. Below is the method for rerouting pins.

Rerouting pin 7 (you need to do this!):

Bend pin 7 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); if you're rerouting pin 4, or LiquidCrystal lcd (8,9,4,5,6,2); in your code if you're not rerouting
Attach a jumper between the pin 7 on the header of the WiFi shield and the pin 7 on the Arduino Uno
Attach a jumper between the pin 2 of the WiFi shield (or the Uno, if that's easier) and the pin 7 of the LCD using the free space of the pin bent above it.

This will isolate pin 7 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 2 on your Arduino to pin 7 on the LCD shield.

Rerouting pin 4 (optional):

Bend pin 4 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); in your code
Attach a jumper between the pin 4 on the header of the WiFi shield and the pin 4 on the Arduino Uno
Attach a jumper between the pin 3 of the WiFi shield (or the Uno, if that's easier) and the pin 4 of the LCD using the free space of the pin bent above it.

This will isolate pin 4 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 3 on your Arduino to pin 4 on the LCD shield.

For number of pins, you should be fine. You can use pins 0 and 1 (TX/RX) as long as you aren't connecting to the computer or any other UART device  (i.e. using the Serial() library). Don't forget you can use the analog pins as digital pins by referencing them as A0 to A5.


You have most of what is needed but you have it structured incorrectly.

Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.

The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.

The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.

This code is untested:

char cMode;

void loop()
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}


To render a UI, you need a PC program. It would handle presenting an interface as well as communicating the user's input to the Arduino over UART. I would recommend writing your own program as it would give you a lot of freedom in the UI design. Processing and Python are good options. To avoid using the IDE, you'll need a USB-TTL adapter cable. If you use the default USB connection, you need the drivers which only ship with the installer AFAIK. To detect the COM port, you can either have the user check the Device Manager or make your program auto-detect it, though this isnt very reliable. This link shows some Python code on detecting the Arduino's port or at least, displaying a list of open ports and allowing the user to choose. You can set the baud rate and other stuff permanently in your code; the COM port is the only variable. Also all handshaking b/w the Arduino and PC can be done without the knowledge of the user.

That said, there are already existing programs (for most common OSes) that can provide minimal functionality. If you dont need a fancy GUI, then putty (on Windows) can serve to read input from a user and pass it on to the listening Arduino. You can use putty's default baud rate (9600) in your Arduino sketch so that the user doesnt have to set this. Again, the COM port must be known. Device Manager is the only real option.

With this second approach, you could make a user enter some string (or even a char) in putty to prompt the Arduino to ask for the SSID and password. Once the Arduino is powered, it does nothing but wait for that input string and once it receives it, it sends something like: Enter SSID: , the user complies (and presses the Return key to terminate) and this is repeated for the password. The Arduino sketch would look like this:

#define MAX_LEN 20  //max length of name or password

char PROMPT[] = "ready\r"  //the initial string input from a user
char SSID[MAX_LEN];  // buffers for the ssid and pwd
char PWD[MAX_LEN];

init_done = 0;  // this var is set when an ssid and pwd have been received

void setup(){
  Serial.begin(9600);
  //anything else
}

void loop(){
  if (!init_done)
    continue;
  //  your other code
}

void get_data(){
  Serial.print("Enter Network SSID: \r\n");
  while (Serial.available() == 0);  // wait for input

  // no timeouts used here; wait till user presses return key
  int i = 0;
  char c;
  while (i < MAX_LEN - 1){  // read chars till the buffer is almost full
    c = Serial.read();
    if (c == '\r') // means end of input
      break;
    SSID[i++] = c;
    while (Serial.available() == 0);  // wait for next char
  }
  SSID[i] = 0;  // null terminate
  while (Serial.read() != -1);  // flush serial buffer

  Serial.print("Enter password: \r\n");  //same as before
  while (Serial.available() == 0);

  i = 0;
  while (i < MAX_LEN - 1){
    c = Serial.read();
    if (c == '\r') // end of input
      break;
    PWD[i++] = c;
    while (Serial.available());
  }
  PWD[i] = 0;
  while (Serial.read() != -1);

  //Serial.print("Done.");
  init_done = 1;
}

void serialEvent(){
  if (!init_done){
    while (Serial.peek() != PROMPT[0]) // read off any garbage
      Serial.read();
    int i = 0;
    while (1){
      if (Serial.peek() == PROMPT[i++]) // compare received chars to PROMPT
        Serial.read();
      else
        return

      if (i == sizeof(PROMPT)){ // read enough chars
        while (Serial.read() != -1);  // flush the buffer
        get_data();  // get ssid and so on
      }
    }
  }


Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.

void loop() {
    int a = ax + 10900;
    if (1) {
      int val;
      val = map(ax, -1300, 1300, 0, 1023);
      Input = val;
      myPID.Compute();
      Serial.println(Output);
    }
  }
}

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.

There is a condition that is always true "if (1)" and so on.

Cheers!


An example how to use NTPClient is available at the projects github

#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

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

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in video here and with it we should be able to get the real time as seen in github example

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

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

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

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.

Check some more examples here


After some more investigation of the IDE folder, I found a text file called boards.txt in the following path.

 [Arduino Path]/hardware/arduino/boards.txt

EDIT: Be sure to make a copy of the file in case you mess up the following part.

Between two series of '#' characters there will be all the information on a specific microcontroller (e.g uno.name=Arduino Uno). Deleting every line of text between the two '#' series will have the desired effect of removing the board from the Tools menu.


One of the parameters that you have to give avrdude is the microcontroller you are using, and then it checks the signature of the micro to ensuere that everthing is ok. this parameter is passed through -p flag

avrdude -p <microcontroller name>

For ATmega328 this parameter should be m328 and in your case, with ATmega328p this parameter should be m328p. All options avalible can be checked in man page.


So, retrieveCallingNumber is documented in here. It "retrieves the calling number, and stores it" in a character array passed as second argument.

The simplest solution to check if this number is among the allowed ones is to construct a string from this and compare it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)

Something like this:

vcs.retrieveCallingNumber(numtel, 20);
String s = String(numtel);
if (s == "allowed number goes here") {
    // toggle LED etc.
}


Sending Variable to IFTTT via ESP32 using Asynchronous Web Server

As already said in the comments you need client code - Here are ready to use blocks for your scenario - NEVER use String class if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:

/* Your constants */
#define READ_THIS_PIN 4
const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
const char MakerIFTTT_Event[] = "stack_exchange_example";

/* Define global char arrays to get rid of string class */
    char numBuf[20];       // We "just know" this is big enough for (un)signed longs
    char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
/* Helper functions for constructing the POST data
    append a string or int to a buffer, return the resulting end of string */

char *appendStr(char *tempChr, char *s) {
    while ((*tempChr++ = *s++))
        ;
    return tempChr-1;
}

char *appendUl(char *tempChr, unsigned long u) {
    return appendStr(tempChr, ultoa(u, numBuf, 10));
}
/*
 This is called once per iteration to read the pin
 and send a POST to trigger the IFTTT/Maker event
*/

void updateEvent() {
    WiFiClient client;

    /* Connect to the Maker event server */
    client.connect("maker.ifttt.com", 80);

    /* Construct the POST request */

    postRequest[0] = {'\0'}; /* Reset char array */
    char *p = postRequest;
    p = appendStr(p, "POST /trigger/");
    p = appendStr(p, "MakerIFTTT_Event");
    p = appendStr(p, "/with/key/");
    p = appendStr(p, "MakerIFTTT_Key");
    p = appendStr(p, " HTTP/1.1\r\n");
    p = appendStr(p, "Host: maker.ifttt.com\r\n");
    p = appendStr(p, "Content-Type: application/json\r\n");
    p = appendStr(p, "Content-Length: ");

    /* We need to remember where the content length will go, which is: */
    char *contentLengthHere = p;

    /* It's always two digits, so reserve space for them (the NN) */
    p = appendStr(p, "NN\r\n");

    /* End of headers */
    p = appendStr(p, "\r\n");

    /* Construct the JSON; remember where we started so we will know len */
    char *jsonStart = p;

    // This example reports a pin, uptime, and "hello stack" change to your need */
    p = appendStr(p, "{\"value1\":\"");
    p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
    p = appendStr(p, "\",\"value2\":\"");
    p = appendUl(p, millis());
    p = appendStr(p, "\",\"value3\":\"");
    p = appendStr(p, "hello, stack!");
    p = appendStr(p, "\"}");

    /* Go back and fill in the JSON length
       we just know this is at most 2 digits (and need to fill in both) */
    uint8_t i = strlen(jsonStart);
    contentLengthHere[0] = '0' + (i/10);
    contentLengthHere[1] = '0' + (i%10);

    // finally we are ready to send the POST to the server!
    client.print(postRequest);
    client.stop();
}


I'have the same LCD from mcufriend and it doesn't work with original UTFT library.

Try modified version from https://github.com/dgolda/UTFT and use:

myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com


Per imjosh's suggestion, I've installed IDE version 1.5.7 BETA and that solved my problem.
Thanks!


Combine bits from two ports into a single byte

Assuming PORTB and PORTD are correctly giving unsigned char values:

result = (PORTB << 3) | (PORTD>>5)

would do it.

As a macro:

#define SCSIBITS ((PORTB << 3) | (PORTD>>5))

Then use like this:

result = SCSIBITS

To make it clearer which specific bits are being used, write:

#define SCSIBITS (((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.

In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write:

#define SCSIBITS ((unsigned char)((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

or:

#define SCSIBITS ((((unsigned char)PORTB & B00011111) << 3) | (((unsigned char)PORTD & B11100000) >> 5)))

Here are a few links to bit-manipulation tutorials:
https://www.hackerearth.com/notes/bit-manipulation/
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm


LCD from Arduino Starter Kit not displaying text

Looking at your first picture it looks like you are wired on 12 and 13 not to 11 and 12 like your sketch specifies.

Double check your wiring against this : https://www.arduino.cc/en/Tutorial/HelloWorld

Also take your multi-meter out and buzz your connections.


The main problem is you are using the wrong interrupt handler. You are setting up Timer1, but the interrupt handler is for Timer0:

boolean toggle0 = 0;

void setup() {
pinMode(8, OUTPUT);
  cli();
//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  sei();
}

ISR(TIMER1_COMPA_vect){  //change the 0 to 1 for timer1 and 2 for timer2
  toggle0 = !toggle0;
  digitalWrite(8, toggle0);
}

void loop() {

}


Turning LED On/Off by using SIM808 with Arduino Mega

Firstly your code was really poorly formatted, making it difficult to see what it did.

After reformatting my best guess as to why you LCD is blank is that the SIM808 is does not have any data available.  print something in the else statement.

Next it could be that the LCD is not working, print something out in setup().

You might also want to add a delay to loop() to prevent the Arduino spamming your SIM808.


How can I pass multiple variables to a function?

You may create a struct with "x" elements, one for each LED:

struct ArrayOfBooleans {
   bool array[4];
};

ArrayOfBooleans myOutputArray;
myOutputArray.array[0] = true;
myOutputArray.array[1] = true;
myOutputArray.array[2] = false;
myOutputArray.array[3] = true;

lightEmUp(myOutputArray);

void lightEmUp(ArrayOfBooleans myOutputArray) {
   bool isFirstLightOn = myOutputArray.array[0];
   // etc
}

NoTE: If you run into Exception 9 issues (using this logic on another board), please check this answer to another post


Thermometer project shows fluctuation due to varying sensor value and voltage

What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

Adding a capacitor between Vcc and Gnd near the sensor, 0.1µf
Adding a low-pass filter on the signal line of the LM35 to Arduino
heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the Vcc and Gnd will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.

The low-pass filter will help give a more filtered output from the sensor with a better response over time.

                2.2k
LM35>---------/\/\/\-0------<Arduino
                     |
                     |
                     |
                    === 1µF
                     |
                     |
                    GND

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.

All three of the above solutions will probably give the best results.

What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.

An example of this would be:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const float powerSupply = 5.0;
const int sensorPin = A0;
const float baselineTemp = 23;
int sensorVal = 0;

//these are NEW
unsigned long lastTime = 0;     // last time reading taken
unsigned long currTime = 0;     //current time variable intialised
float AverageReading = 0;

float _readingAv = 0;   // static variable for keeping the averaged reading
int _readingsCount = 0;
int _readings = 100;     //the number of readings to take

void setup() {
  Serial.begin(9600);
  //  lcd.begin(16, 2);
  //  lcd.print("Temperature:");
}

void loop() {
  currTime = millis();

  if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
    sensorVal = analogRead(sensorPin);

    if (_readingsCount < _readings) {
      _readingAv += sensorVal; //add the current value to the last
      _readingsCount++;
    }
    else {
      AverageReading = _readingAv / _readings; //get the average
    }
  }
  else {
    Serial.print("Sensor Value: ");
    Serial.print(sensorVal);

    float voltage = (AverageReading / 1024.0) * powerSupply;
    Serial.print(", Volts: ");
    Serial.print(voltage);

    Serial.print(", degrees C: ");
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);

    //~ reset the values used by the previous function
    _readingsCount = 0;
    lastTime = currTime;
    _readingAv = 0; //Important to set this back to 0 so not to get odd values

    // set the cursor to column 0, line 1
    // (note: line 1 is the second row, since counting begins with 0):
    lcd.setCursor(0, 1);
   // print the number of seconds since reset:
    lcd.print(temperature);
    // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
  }

}

Probably a better version of making filtering code of the LM35.


https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55

Defines the function in TimerOne called SetPeriod(). That will change the period.


How can I swap a servo with a stepper motor?

Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like this along with your 28-BYJ48 stepper motor.

Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.

(I've often found this simple piece of code really handy for troubleshooting!)

#include <Stepper.h>

const int stepsPerRev = 2048

// initialise the stepper library on pins 8, 9, 10 & 11
Stepper myStepper(stepsPerRev, 8,10,9,11);

void setup() {
  // set the speed
  myStepper.setSpeed(4);

}

void loop() {
  // step one revolution in one direction:
  myStepper.step(stepsPerRev);
  delay(1000);

  // step one revolution in the other direction:
  myStepper.step(-stepsPerRev);
  delay(1000);

}


Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?

Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)

I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.


Need to make an action just once when condition is reached

A possible solution to your problem can be the following:

#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;
bool first = true;
bool second = true;
bool third = true;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }
  delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.