Digital selection for gain control not working instead showing 0

pinMode( K1, INPUT );

with

    if(K1 == LOW && K2 == LOW)

makes no sense. K1 is a pin number. LOW is a macro for 0 (HIGH for 1). You are comparing a static pin number against a static number.

If K1 is not equal to 0, the inner part of that if statement can never be reached.

What you meant to do was "if the voltage at the pin K1 is low". For that you need to read out the current value of the pin and check it.

For that you must replace your if(K1 == LOW) type statements to if( digitalRead(K1) == LOW).

I'd also like to mention that you must have a pull-up on your buttons for this "LOW"/"HIGH" logic to work. Either externally, or use INPUT_PULLUP instead of INPUT in pinMode.


I've resolved the issue by using AT commands instead of the GSM library provided through Arduino.

if(sendGPRSCommand(F("AT+CPIN?"),100).equals("AT+CPIN+CPIN:SIMPUKOK")){
    Serial.println(F("PUK is requested, entering it now"));
    String cmd = "AT+CPIN=\"";
    cmd.concat(PUK_NUMBER);
    cmd.concat("\",\"");
    cmd.concat(PIN_NUMBER);
    cmd.concat("\"");
    sendGPRSCommand(cmd,100);
  }

This code checks if the PUK code is requested, this is the case when the pin_query is -1 or -2 (see question). When the PUK code is requested the new PIN (which is still the same pin as the old one) is given in combination with the PUK code.
The AT commands were found in this manual.


what voltage level is a digital low for the interrupt mode LOW?

It would be great if I could set up an interrupt to turn on an LED
when the batteries were getting weak

That won't work. The thresholds for the pin registering LOW or HIGH
depend on the supply voltage. Very roughly:

a pin in guaranteed to register LOW if its voltage is below ⅓ Vcc
it is guaranteed to register HIGH if it's above ⅔ Vcc
nothing is guaranteed between ⅓ and ⅔ of Vcc.

For the exact voltage levels, you should check the datasheet.
Note also that those are guaranteed levels. The actual thresholds are
closer to ½ Vcc, with an hysteresis of roughly Vcc/10.
For detecting a low battery condition, you should use the ADC, combined
with either a voltage divider on Vcc or the internal bandgap reference.


If you are not getting anything on the receiver, then the receiver is definitely the problem. These units will boost the gain until it get some signal, any signal.

You should be able to power the receiver + and GND (I have one, which ran on 5v, I can't see if these are the same), and put a multimeter from GND to Data, and you should get about half of Vcc, probably fluctuating a bit. If you look at the same with an oscilloscope, it should fluctuating wildly between 0 and Vcc volts. All of this should work without a transmitter, and without an Arduino (you will need a power supply for the receiver).

Note: this is from memory, I don't have mine here to test.

Once you are getting "random data" (background noise), you can progress to sending a signal.

Note that you should keep your "1"s and "0"s balanced to get a clear signal - check out Manchester encoding (this encodes a "1" as "1,0", and a 0 as "0,1", so there will be a perfect balance). You might also want to send a 1010101010 at the start - this gives the receiver a chance to adjust the gain to the correct level. Or, you can use some width-based encoding (e.g. "slow 1, slow 0" for a "1", and "fast 0, fast 1" for a "0").


Problem I see is that the request is incomplete - the server will be waiting for your payload.

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");

You haven't specified a Content-Length header so the payload should start after the headers finish - but you don't send anything.

You need to (at least):

add a payload or
add a Content-Length: 0 header or
add a payload with a matching Content-Length: header.

You can use curl to see a full set of valid POST headers like this:

curl -v -d "" http://localhost

You can use Chrome and Firefox's Web Inspector's Network tab to look at the raw headers of requests too.


Could someone explain this code that sets up the software serial port data rate?

You're confusing "data rate" with "baud rate".

The baud rate is the speed at which bytes are transmitted over the wires, and is set with mySerial.begin(9600);.

The data rate is the speed at which data is sent over the serial port, and that is set by the delay(10000); which dictates how often "test I am master  " is sent and any incoming data is checked for and echoed.


My issue has ultimately come from some memory differences between the ATTiny88 and the ATMega88 - the latter has twice as much SRAM - 1 kB. There normally have not been any warnings on this running out of RAM issue except for once - can't recall how but Arduino IDE did warn.

However, until I got to the bottom of it there have been some digging that had to be done. Like getting used to the programmer either working as expected, or erroring and failing, or erroring and not failing. Then there are the, sometimes changing, folders into which Arduino IDE outputs its files. Also there are non-working board configurations causing the used Wire libraries to issue read and write requests followed by just a NAK. Oh, and not to forget about the messed up signals - turns out they weren't messed up, just the logic analyzer was.


WiFiEsp not working on Software Serial, working fine on Hardware Serial

If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.

You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -> ESP) that fast. You need to send it the command:

AT+UART_DEF=9600,8,1,0,0

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:

AT

The ESP should respond with

OK

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).

Update:

  I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.


Unexpected result with the GSM module A6

Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

  AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:

mySerial.begin(115200);

to

mySerial.begin(9600);

And now all is well :D


As stated in other answers, sound recognition is completely out of the
realm of what an Arduino can do, but recognizing a specific pitch is
possible.
However, contrary to previous answers, I would recommend against using
an FFT. The FFT is the right tool when you need to get all the
frequency components. It is, however, overkill when you want to look at
a single frequency. Given the low processing power at your disposal, I
suggest you try instead an homodyne detection scheme. An Arduino
Uno, or similar board, has enough resources to sample an input at
9.6 kHz, and extract in real time a specific frequency component.
See for example this homodyne detection program.


With the help of Majenko and jsotola in the comments, I've got it fixed! It was the text I was displaying in the Serial Monitor that was slowing the display down. Here is the updated program that works:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
// THE NEXT TWO LINES HAVE BEEN COMMENTED OUT FOR IT TO WORK
   // Serial.println("The value of buttonPress is:  ");
   // Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I'm leaving the program modifications here in case anyone else gets the same problem.


Custom Bootloader on Atmega328p - PU - 28 pin DIP

The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.


Connect USB cable to GPIO pins on an Arduino Uno

The reason you are confused about which wires go where is simply because the Uno has no connection on it for a USB cable's wires.

You cannot directly interface an Uno to a USB port without extra hardware.  What hardware you require depends on exactly what it is you think you are trying to achieve.

(There have been some attempts to create a USB device interface purely in software, but personally I wouldn't touch it with a barge pole - the GPIO of the Arduino is not electrically compatible with USB.)


Your problem stems from this line:

#define ADS1219

You define the macro ADS1219 as empty. From that point on all references to ADS1219 get replaced with nothing. For example:

class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

becomes:

class {
public:
 ();
 void begin();
 void printHello();
};

And

void ADS1219::begin(){
 Serial.begin(9600);
}

becomes:

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

By using the same name in your header guard as your class name you screw everything else up.

I always use strict rules for header guard macros to ensure that they never conflict with anything else.  You should change yours to read something else.  I would use:

#ifndef _ADS1219_H
#define _ADS1219_H

// ... content

#endif

You are also lacking the parenthesis in the constructor implementation:

ADS1219::ADS1219{
 Serial.println("New object created!");
}

should read:

ADS1219::ADS1219(){
 Serial.println("New object created!");
}

And you don't give your ads variable a type and you don't want to use new:

ads = new ADS1219;

should read:

ADS1219 ads;


I had this issue and it was because the port was not set in my Arduino IDE.
I fixed it by going to Tools -> Port, and selecting my usb device.  In my case it was called /dev/cu.SLAB_USBtoUART


What does a tilde (~) mean as annotation for a data pin?

It means the pin can be a PWM output for use with analogWrite().


It uses the 2.4 GHz band

Does this refer to the frequency of the EM waves that the device uses to communicate?

Yes. It generates (and receives) radio waves in the region of 2.5GHz.

If used in open space and with lower baud rate its range can reach up to 100 meters.

I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

Think of it like talking to someone. If you're stood right next to them you can speak nice and fast and they can understand you. Your speech comes across nice and clear.
However if you're the other side of a quarry you have to shout really loud, and if you talk too fast they can't understand you. You. Have. To. Shout. Slowly. so that they can understand you.
The environment makes a lot of difference to how your speech propagates. In large areas there's lots of echo and other things.  It's similar with RF communications. There's more noise and things that can interrupt communication. By having lower baud rates you're giving the receiver more time to understand what it's receiving and make sense of the data.

The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

There's a number of different factors at play here. First there is the "Bandwidth" of the channel. This is the maximum amount of data that can be squeezed into a particular carrier frequency with a particular amount of "space" around the signal. You can think of the channel width as the diameter of a pipe. The wider the pipe the more water can be pushed through the pipe per second.
You want to slice the RF allocation up into enough channels to give enough concurrent access to lots of devices, but at the same time you want to have enough bandwidth per channel that you can transfer reasonable amounts of data.
It's all a balancing act.
Nordic decided 125 channels was the optimal balance for their application.
One nRF24L01+ can work at one frequency at a time. That's not to say you can't instruct it to change frequencies at any time, but it can only be listening on the one frequency at once. Just like a normal FM radio - you can only listen to one radio station at a time.
But the nRF24L01+ protocol uses addresses within that one chosen channel, so lots of devices can all be on the same channel to talk together, and each is distinct by its address.
The protocol also includes the concept of "pipes" which are virtual wireless circuits between two physical devices. Once you have configured a pipe with an address any other device can communicate with that pipe. You can configure up to 6 pipes, so up to 6 devices can send to the same target at the same time and each devices data is kept separate and distinct from the others. It's kind of like having 6 serial ports all connected to different devices at once.


Getting two trinkets to talk to each other via the serial pins

1) you should use if (Serial.available()) before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

void loop()
{
  if (Serial.available()) {
    Serial.println("reading bytes");
    size_t l = Serial.readBytesUntil('\n', state, 10);
    state[l] = 0;
    Serial.println(state);
  }
}


Difficulties programming Arduino uno for 24 hour cycle

On the Uno unsigned int is a 16 bit number. That means, that it can hold values between (and including) 0 and 65535. If you try to write a bigger value to this variable, it will cut of the higher bits, so that the rest fits into 16 bits. That gives you a totally different value, which is significantly small than 24h.

The solution is to use a bigger variable type for totalTime.
 You can use unsigned long, which has 32 bits and can hold way bigger values ( 0 to 4,294,967,295 (2^32 - 1)). That should be plenty enough for all your cases.


How can I test/demonstrate what the serial input and output buffers are?

You can think of the incoming serial buffer as a bucket of water under a dripping tap. Next to the bucket is a cup.

Water arrives through the tap and drips into the bucket. When you want to get some water, if there is enough water in the bucket, you dip the cup in and remove a cupful of water. If there isn't enough water you don't get anything in your cup.

If you don't dip the cup in for a while too much water will dribble into the bucket and it will overflow all over the floor.

It's exactly the same with serial data. It arrives through the UART hardware and is placed into the "bucket" by the UART receive interrupt. If you don't dip your cup in fast enough (Serial.read()) the bucket will overflow and any new data that arrives will spill onto the metaphorical floor.

To test this out you can just send more data to the Arduino than will fit into the serial buffer (typically 64 bytes) without reading any. Then after you have finished flooding the buffer you can read what is actually in the buffer and send it back again (maybe formatted nicely) so you can see what has actually ended up in the buffer and what hasn't.

One quick and dirty test would be to send the raw bytes 0 to 255 to the Arduino, then after a delay read them back and display the DEC values for them (Serial.print(Serial.read(), DEC))) to see exactly which bytes arrived and which didn't (hint: you should see the numbers 0 to 63 if the buffer is 64 bytes big).

For the transmit buffer it's slightly different.  You can think of it more as a bucket with a small hole in the bottom.

You pour data (water) in the top at whatever speed you want, and it trickles out of the bottom at a pre-set rate (the baud rate - the size of the hole). You don't like wet messes though, so if the bucket is full you wait a while before putting more water into it. Just like with serial - if the transmit buffer is full any attempts to add to it will block until data has been sent out by the UART transmit interrupt.


esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE

It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: ESP8266FS


ESP8266 Arduino Json object array deserialisation into struct

No memory is allocated for the strings.
You should declare your struct like so:
struct Departure {
   char destination[32];
   char departure[32];
   int  deviation;
} depart;

This assumes the max length for both strings is 31 characters.
Then, pass the max size to strlcpy():
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["Destination"], 32);
strlcpy(dep_arr[i].destination, ResponseData_Metros[i]["ExpectedDateTime"], 32);

If your strings are very long, you can use a String instead of char[].
See the example JsonConfigFile.ino, it shows all of this.


Whenever making ajax calls from/to different hosts (as your pc and the yun) you should use JSONP.


Arduino Uno + Sim808: Using HTTP client for GPRS GSM

Start Arduino IDE, open the Library manager, search for SIM800 and there is 3 libraries available there that you can install. The advantage is that this libraries is kept up to date and when a new version is available you will get a notice to upgrade.

There is a HTTP PUT/GET library "HttpClient" that can be installed the same way as above.

Or

If you googlem using "sim800 library arduino" you will find several libraries like:

https://cristiansteib.github.io/Sim800l

or on github:

https://github.com/search?l=Arduino&q=sim800&type=Repositories&utf8=%E2%9C%93

And as I understand it the 808 is GSM/GPRS + GPS, so the GPS features isn't normally covered by these libraries.


Controlling a DC motor with an external power source

Seeing as you want to use a 12V battery, you should try an external motor controller. You would essentially connect the Arduino to the controller, then the external battery and motor to the controller. Dimension Engineering makes several high quality motor controllers that are compatible with Arduino and can handle the voltage (like this controller). The site also includes Arduino libraries, documentation, and all the specifications on every product. I have used several of their products with my Arduino Uno and have had no problems.


How do I make a character array scanner properly?

If I had to guess, I'd make a loop that will reasign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

Yep, that's pretty much it...

Here's how I do it:

char data[10];

if (Serial.available()) {
    char inch = Serial.read();
    for (int i = 0; i < 9; i++) {
        data[i] = data[i+1];
    }
    data[9] = inch;
}

Every incoming character gets added to the end of the array after everything else has been shuffled down one place.


Making a PID Controller for BAR 30 pressure sensor

A PID controller should be a good match for your application, but it appears that your code doesn't take advantage of the PID_v1 library at all; a PID_v1 object is never declared, and it appears you are attempting to manually compute what the PID library is designed to do for you automatically.

I would recommend you 'start slow and simple' by learning how to use a PID controller in its most basic form.  The PID library has a very basic example, which I have modified slightly to demonstrate how a PID controller works.  I tested this example with a UNO, a potentiometer (variable resistor) and a capacitor. The resistor and capacitor values aren't critical - I used the first things I found in my parts box.  The output on Pin 3 is a PWM pulse train signal, and the resistor/capacitor combination filters this pulse train to a variable level analog signal, which the PID controller sees as the analog 'Input' on A5.

Once you have this running, you can vary the pot value to see how the PID changes the output value in order to achieve the setpoint value on the input, and you can vary the setpoint and PID parameters to play around with different configurations.  Once you are comfortable with basic PID operation, you should then be able to configure it properly for your application.

Hope this helps,

#include <PID.h>

 //Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, 2, 5, 1, DIRECT);

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

    //initialize the variables we're linked to
    //Input = analogRead(0);
    Input = analogRead(A5);  //I used A5 as A0 was unavailable
    Setpoint = 100;

    //turn the PID on
    myPID.SetMode(AUTOMATIC);
}

void loop()
{
    //Input = analogRead(0);
    Input = analogRead(A5); //I used A5 as A0 was unavailable
    myPID.Compute();
    analogWrite(3, Output);
    Serial.print("Input = "); Serial.print(Input); Serial.print(", Output = "); Serial.println(Output);
    delay(100);

}


Refreshing a web-page hangs after few times

The code you have that says readString += c has to allocate a whole new string whenever it runs out of space for more characters. All those allocations are filling up memory.

Instead of the String class, use a single C character array, e.g.

char s[128];

that is big enough for whatever you put in it.

If it helps, I wrote a simple arduino web server for my own project, and if you look at the code here that may give you ideas for how to implement this.


How much power can the Teensy 3.2 deliver to external components?

No.  You should provide your own regulator or supply for the servos specified voltage.

This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.

Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.

Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.


SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V


Arduino Mimicking Voltage Dividing Keypad / Matrix

Reading the leds would work. Depending on the voltage going out of the shift register, you might need to add a buffer chip, to lower the voltage.

For the keypad I'd probably go with a variable resistor, better known as a digital potentiometer.

You could probably add a way to also read the keypad, from the arduino. Which might be useful, maybe.


Here is is a picture of how I have seen the sensors connected.  Is this how your is?


Using Multiple identical sensors - Beginner

If you mean this kind of sensor:

The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.

The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be LOW, otherwise HIGH.


Accel Stepper help, stepper not going backwards

Work through your code. When it gets to the target position, your loop looks like this:

void loop()
{
    // Change direction at the limits
  stepper2.moveTo(user);
  stepper2.setSpeed(300);
  stepper2.runSpeedToPosition();
    stepper2.moveTo(-stepper2.currentPosition());
    stepper2.setSpeed(300);
    stepper2.runSpeedToPosition();

}

So you say, move to position 'user', then move to position '-stepper2.currentPosition'. Then as the loop comes around you again say move to position 'user', and so on.

The loop will repeat hundreds if no thousands of times per second, so you are basically telling the stepper motor to change direction thousands of times per second which will be why the motor starts vibrating when it gets to the user position.

If, just for the sake of argument, you were to move the first three lines of code in the loop() function to the setup() function, what behaviour do you think you will observe?


The easiest way is to use the settings:

Tools > Board > Arduino Pro or Pro Mini

Tools > Processor > ATmega328 (3.3V, 8MHz)

The problem with that is the Pro Mini bootloader is 2kB and has a bug that causes an endless reset loop if you do a watchdog reset.

The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.

After selecting the correct configuration for your hardware from the Tools menu, do Tools > Burn Bootloader, which will set the fuses on your ATmega328P and upload the correct bootloader.


Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow

Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.

The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent and in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.

With your sketch, you have to open the serial monitor for both the Master and Slave.

You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.


Struggling to understand how Bluetooth serial is related to USB on Arduino

I don't actually know what a UART is

UART (Universal Asynchronous Receiver Transmitter) is the technical term for the communication interface, which is called Serial in Arduino speak. It's often called UART, because that is more precise, since there are many different communication protocols, which also work serially (meaning transferring data bits one after another in contrast to parallel, where multiple bits are transferred simultaneously), like I2C, SPI or USB. All serial protocols, but totally different from the Arduino Serial interface. Yes, this is a bit confusing. I guess the Arduino term Serial was coined to make the learning curve less steep for beginners (hiding complexity can also make things confusing unfortunately).
So UART is the same as the Arduino Serial interface.

once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?

Here it is good to know, how the USB communication works on the Uno. The microcontroller on the Uno (Atmega328p) does not have a native USB interface. So it cannot speak to USB itself. For that there is an extra microcontroller on the board (I think an Atmega32u4). This controller has a native USB interface and it acts as a USB to Serial bridge (it creates a virtual serial interface on the PC and translate between that and its physical Serial/UART interface). The Atmega328p (which you program with your code) has it's RX and TX pins connected to the RX and TX pins on the Atmega32u4, which can then translate between the Serial/UART protocol and the USB protocol. Thus the Atmega328p doesn't know anything about USB. I just talks via Serial/UART to the Atmega32u4. In fact it also doesn't know anything about bluetooth. Most bluetooth modules for Arduino are also just bluetooth-Serial bridges
Now you need to know, that Serial/UART is made for one-to-one connections. With multiple devices you can get problems, when multiple devices try to send data at the same time. I this case (BT module RX to Arduino TX and vice versa) you would get garbled data, if you try to simultaneously send data from bluetooth and USB to the Arduino. The signals would overlap on the Arduinos RX pin, corrupting the data.
That means, that you don't want to send from both interfaces. In fact it is the easiest way to just use one Serial/UART  interface for only one device. If you leave the Serial Monitor (or any other Serial communication program) closed on the PC, the PC will not interfere with the communication. Though you need to disconnect the bluetooth module, when you write your program to the Arduino, since this is done via Serial and you don't want it to meddle with the data.
So in result the bluetooth module will not "replace" the connection through USB. It will be added and it is your duty to prevent data corruption.

Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor

Yes. You don't need to use 9600 baud necessarily. The only requirement is, that you use the same baud number in both sketch and Serial Monitor. That number just represents the speed, that the data is send in. Both sender and receiver need to agree on the same communication speed, or the receiver will not be able to read the data. Imagine someone talking to you, but talking twice the speed with that you are able to understand the words. You will not be able to understand much, because the speaker is just too fast. Either you would need to change your hearing/understanding speed or the sender needs to change it's speaking speed, to make the two match.
9600 baud is just one of the standard baudrates, though one of the lower ones. If you need it to be faster (maybe because you are sending much data in fast succession), you might want to use a higher baudrate.

Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital

That is up to you. Serial/UART is just a communication interface. How it is used is up to you. You already have seen, that it is often used to output text for a user to read over the Serial interface, often used as a way to debug the code by sending specific text at specific places in the code. Since that connection works in both ways, you can also program the Arduino to receive commands over Serial/UART and then act upon them.
Here the overlaying communication protocol comes in. Serial/UART just transmits a series of bytes over its two lines. It doesn't care, what these bytes mean. It can be text (for example encoded via the ASCII standard, as the Serial Monitor does), or it can be just some binary data. Also there is no concept of "messages". There are only individual bytes and you don't have control over when exactly they are sent. So to make meaningful use of Serial/UART you need to use an extra communication protocol on top of Serial/UART, that the receiver understands.
When you send text to the Serial Monitor you are the receiver. Thus you would send text (because you can understand text) and a natural way for humans to distinguish individual messages is to use a delimiter character. In normal text that can be a period, though in this field going to a new line has somewhat evolved to the standard (so the delimiter character is the newline character '\n'). If you read the delimiter character (either yourself on the Serial Monitor, or the Arduino in your program), that marks the end of the message. You can also use that text based approach in your Arduino program (and I would say that is the easiest way). Though you don't need to. You could also use any binary protocol on it (or even invent your own protocol).
I would suggest you look at the examples in the Arduino IDE, that involve Serial and maybe try some tutorials on the web. There are many of them available.

Sending code: Can I still send code through Bluetooth without needing a USB connection?

You don't need an USB connection for Serial/UART to work. In fact the Atmega328p, which you program on the Uno, doesn't care about the USB connection at all. It only knows Serial/UART.

I hope that gave you a good overview over that topic. When you understand these core concepts you will be able to understand the tutorials and examples on the internet.


From your comment of Jul 1st, I understand that you can program your
server in PHP. Then, and to expand on my own comments, I am only
recommending that, whatever Web API you design, you keep it as simple as
possible. For example, for telling the Arduino whether it should keep
the shutter open or closed, you could write something like this in PHP:

header('Content-Type: text/plain');

if (user_wants_shutter_open())
    echo "open";
else
    echo "close";

In particular, it makes absolutely no sense to write a PHP program that
generates an HTML document. Consider that the Arduino is a very low
powered platform: there is no point in having it process more than a
handful of bytes when you only want to communicate a single bit of
information. And you should know that there is really nothing wrong with
using HTTP to transport plain text (but you should use the header
Content-Type: text/plain). If you want to send a more complex set of
data, you could use something like text/tab-separated-values, or maybe
even application/json.

Concerning web scrapping, it is a solution to a specific problem, the
problem being that the server returns the information in a format that
is not very well suited for machine consumption. You do not have this
problem. Obviously, you could create the problem by having your PHP
return an HTML document, and then you could apply the solution. My point
is that it is better to avoid creating the problem in the first place:
just return the information in a format that is as easy to parse as
possible.


Is it possible to program Arduino in transpiled JavaScript?

Even if such a transpiler exists (which I don‘t know) you will still have to deal with the loop structure and the fact that you should avoid using delays. On a microcontroller you have to forget about things like multithreading and even dynamic memory allocation should be used carefully.
Most of those things that make a programmer‘s life easy on bigger systems are usually paid with ram or cpu power, but on a microcontroller with some kB RAM there are only few resources to pay with.

So my recommendation is to learn C++ instead of looking for ways to convert code from another language, which will probably introduce its own problems. You‘ll soon find yourself one layer below and there are exciting things that higher languages hide from you.


Arduino port not showing serial USB Mac OS El Capitan

Change USB ports
Check your Tx and Rx pins aren't connected to ANYTHING.
Reboot your Mac.
If you're really desperate, change OS.


Ethernet shield/WebServer problem: 'server is at 0.0.0.0'. Any suggestions how to debug it?

That's what it's supposed to be. It's called INADDR_ANY. Read an introductory text on networks and you'll understand what that means.

If you try to connect to the IP address you specified, you'll see that you can indeed connect.


Although the Arduino only has one CPU core and can only execute one program instruction at a time, it's not limited to only doing one thing at a time.

An MCU is a complex device with lots and lots of peripheral devices built into it. The CPU is only one small block of the overall device.

Much of a program is merely instructions telling the peripherals how to perform.

For instance, when sending data through Serial the CPU doesn't say "Send this bit. Now wait. Now send this bit. Now wait again" - instead it just says "Here's this byte to send. Now go and send it and tell me when you're done". The UART peripheral then sends the byte by itself with no further input from the CPU leaving the CPU free to do other things.

Then there's the Timer peripherals.  The CPU sets them up to count from a clock source, and do different things depending on different events, like a specific number is reached in the counting, etc. The CPU has no need to go "Count up one. Count up one. Count up one." - it just goes "Count up from 0 using this clock source and tell me when you reach 100" (for example).

Similarly, there are "External Interrupts". The CPU doesn't need to sit watching an IO pin all the time, going "Have you changed yet? Have you changed yet? Have you changed yet?" - it just goes "Tell me when you have changed" and the CPU goes off to do other things.

Of course, all these things have caveats. The biggest is that if the CPU is doing something very timing critical, such as "bit banging" serial data manually through a GPIO pin (for example with SoftwareSerial) it can be set to ignore all these interrupt signals from the peripherals. That means, if you're using an "External Interrupt" to count pulses, and you have to use SoftwareSerial to communicate, it's possible that SoftwareSerial's sending or receiving routines could cause the detection of a pulse to be either delayed (not really a problem) or to be missed completely.

So you don't want to use SoftwareSerial if it can be avoided if you want to use External Interrupts for this kind of operation.

The other option is to use a timer. I mentioned that they just count up from 0 (or they can count down, too) using a configurable clock source. That counting happens completely independently of the CPU, and carries on regardless of whether interrupts are enabled or disabled. And the great new is that most timers can be configured (depending on which Arduino you use) to use an external signal as the clock source for the counting.

That means you can configure a timer to count your pulses for you regardless of what the CPU is doing. All you have to do is every so often (how often depends on how frequently your pulses arrive - the timer has a limit on how many it can count before it overflows) ask the timer for what it has counted up to and reset its count to 0. That could be done as part of your "sending" routine. Get the count, reset it to 0, and send the results.


Arduino Uno ADCH register stuck at 255 when read from ISR

It would seem the problem lies here:

// Set Register to all zeros since Vref
// will be set to internal voltge and
// analog pin A0 is used.
ADMUX = 0x00;

According to the datasheet, the bits REFS[1:0] of the ADMUX register
select the voltage reference as:

00: AREF, Internal V ref turned off
01: AVCC with external capacitor at AREF pin
10: Reserved
11: Internal 1.1V Voltage Reference with external capacitor at AREF pin

Settings those bits to zero means that you are now supposed to provide
your own reference through the AREF pin. If you want to use the 5 V
supply as a reference, you should set them to 01. This is confirmed by
the block schematic. Here is the part of that schematic relative to the
reference voltage:

When REFS0 is zero, the highlighted transistor does not conduct, hence
the only way to provide a voltage reference is through the AREF pin.


What happens, memory-wise, when I call a function from another function?

The clue is in those last two lines:
    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Let's tear them apart and see what they actually do.
ErrorResponse::componentNotFound(instruction).output(this->serial);

Call the static function componentNotFound with your instruction, then take the object that is returned, and call the output() method on it passing this->serial as a parameter.
The hint there is take the object that is returned.
componentNotFound() returns an object. That object has to be stored somewhere. That "somewhere" is on the stack.  And stack space is allocated during the function preamble.  That's the bit of code that runs at the start of the function allocating stack, pushing registers to the stack, etc.
The same happens in the second line:
TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Create a new TerminationResponse object and call the output method.
All that goes on the stack.
It's not the calling of the function that is using the memory, it's what the function is doing that is using the memory.


Running both sensor and addressable LED strips at a same time?

Rewrite without using delay(). Or alternatively, do the test inside the for loop as well, eg.

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);

    // ----------- ADD THESE THREE LINES ---------------
    currentSensorReading = analogRead(sensorPin);
    if(currentSensorReading is NOT in range of certain values)
        return;

  }
}


"The line with the error" falls outside of any functions. In C and C++ we write executable code inside functions. You placed your

threshold=maxA0-40;

(and everything that follows) outside of any functions. Hence the error.

Errors like this are typically cased by improper placement of { and } braces. But this is something you have learn to check for yourself. Most C or C++ oriented code editors can usually help you with this. And proper code formatting can help you with this too. What you have now is such a mess, that a simple error is virtually impossible to see.


Need a sensor to make ball roll away from pet but which sensor?

Perhaps an RFID tag on your dogs collar and a reader inside the ball will work.
You will just have to find a reader and tag combination that can work from the range you need, I think some RFID can work from over 1ft.
EDIT: You will need active tags (battery powered) to get over a foot range.

PIR sensors detect heat given off by humans and animals, so they make work through the ball. (not totally sure though).

Edit: i think PIR that is capable of detecting small animals may be your best bet you would just have to calibrate the range of detection some how


Read both battery voltage and analog sensor value with NodeMCU ESP8266

to read VCC voltage, ADC pin must be kept unconnected. Additionally, the following line has to be added to the sketch:
  ADC_MODE(ADC_VCC);

The setting of a purpose of the analog pin of esp8266 is at low level and must be projected into the compiled binary. It can't be changed at runtime.

On esp8266 if you want to use the power sensing or to have more ADC you must use an external I2C ADC.

reference


As I noted in a comment to the question  Arduino LCD is displaying gibberish, sometimes,  a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD.  If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.

Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem.  That fixed the problem in the case of the linked question.

If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.


LCD screen stops displaying after DC motor starts

A brush DC electric motor and many other similar devices will produce random noise as well as uneven power demands and should be powered independently of logic circuits such as processors and LCDs.  It is very difficult to mediate noise sources and almost always better to remove them from where they are causing harm or unexpected results.

It is also important to power a project with a supply capable of providing more than the expected amperage during highest demand.  Many will calculate the highest amperage demand and select a power supply which is rated at double the amperage.

If you are using batteries, note that a 9 volt battery (which usually contains 6 cells) on average supplies about 500mAh.  Not much and likely not enough to run a motor with out momentarily dropping the voltage.  Where as a D-size battery supplies about 15000mAh.  Different battery chemistries change the mAh rating drastically.  500mAh and 15000mAh are about what one may expect from Alkaline batteries.

If using a USB power source, note that older USB ports are only obliged to supply 500mA at any given time.  If this current limit is exceeded, the voltage may drop under 5 volts.

There are many designs on the internet where the motor is powered from the Arduino.  This may be possible for smaller motors however you are having unexpected behavior.  Consider using one or more of the following suggestions to mitigate your problems:

Avoid low mAh batteries such as common 9 volt batteries.  Instead use a battery that can provide higher mAh like D Size cells.
Avoid powering noisy or current demanding devices directly from the Arduino.  Consider an independent power supply and use a common ground.
It may be possible to use a single power supply with good results if the power supply is rated at higher amperage than the peak total maximum amperage.


Can Chirp Waves be sent using JSN-SR04T?

As I googled the sensor, I found various sites stating, that a JSN-SR04T behaves exactly like the HC-SR04. The difference is mainly the water prooving.

So the answer is: No, you can't do this. The square wave, which drives the ultrasonic transducers, is generated by a hardware circuit and is not meant to be changed. To output a chirp wave you would need to rebuild the signal generation and measurement hardware (leaving only the transducers unchanged). At that point you may just buy the pure ultrasonic transducers and build the rest yourself.


You have several options. One is Bluetooth and another is nRF24L01+ 2.4GHz Wireless Transceiver. I love the nRF24L01+. They are cheap and there are tons of examples online.

The concept with the nRF24L01+ is to connect the RF24 to a Ft232rl Ftdi Usb to Ttl Serial Adapter. The Ft232rl  connects to your PC. Most modern computer languages support communicating via Serial. This is the way to go.

Google around for a ton of tutorials


Changing address of MPU 9250 connected to ESP32

You have only two choices with this device on an I2C bus.  As stated in the datasheet:

So it's either:

0b1101000
0b1101001

The AD0 pin selects which of these two addresses are used.
The complete datasheet can be viewed at the following link as well as other places:
Datasheet


ATtiny85 AC Phase Control for dimming a light bulb

So I think there were (was?) two issues.

1) Pin change interrupts on the Attiny85 are triggered on rising and falling edges which I think was causing the flickering.

I changed the code to rising edge only triggering:

ISR(PCINT0_vect){ //interrupt looking for zero crossing
        if (digitalRead(4) == HIGH){
                TCNT1 = 0;   //reset timer - count from zero
                OCR1A = level;
                TCCR1 = B00001011;// prescaler on 1024, see table 12-5 of the tiny85 datasheet
       }
}

2) Attiny85 #reset pin. Pulled that guy high with a resistor.

Anyways, here's the oscilloscope and dimming led blub video: youtube


How to I press a button once to display text and again to remove it?

You need to somehow debounce the button. Using a long delay in the loop
(your delay(100)) can do the trick, but it's probably not the best
way, as it will slow down anything that you may later add to your
program.

Better would be to write your own debounce function, or to use one of
the libraries that already implement that. For example, with
Bounce2, you would write
something like:

#include <Bounce2.h>

const int buttonPin = 8;
Bounce button;       // debounced button
bool textDisplayed;  // whether the text is displayed or not

void setup()
{
    button.attach(buttonPin, INPUT);

    // etc...
}

void loop()
{
    // Read and display the analog value, then...

    // Update the state of the debounced button.
    button.update();

    // Toggle display on rising edges of the button.
    if (button.rose()) {
        lcd.setCursor(0,1);
        if (textDisplayed) {
            lcd.print("   ");
            textDisplayed = false;
        } else {
            lcd.print("YES");
            textDisplayed = true;
        }
    }
}


MAX7219 7-segment 8-digit display in wrong order

If you had three separate boards that you had chained together I would be surprised if one of them was wrong, but looking at the picture it looks like one board and I would think it was more likely that one display was incorrect.

I can't see your code, so I can't say if there is a bug in it or not.  It is possible that you have done something unusual, you might want to post a MINIMAL example to let people give it the once over.

As far as I know there aren't any "configuration settings" on a Max7219 to cause the affect you are seeing.  The fact that the 3rd display is correct implies that the tracks on the PCB are correct and its the IC that's got its wiring backwards, but that's a daft idea.

You might be able to work out if a track is wrong, or such like, but it would be so much easier to fix in software.  When you write to the display add an extra function that traps calls to the middle segment and flips the digits round (so tmp == digit[7]; digit[8] == digit[0]; digit[0] = tmp; // You know what I mean).


Multiple HC-SR04 with one 5v 7805 regulator

You really could benefit from a DC/DC switching power supply.  For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.

That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together?  If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results.  Same goes for the 3rd sensor.


Arduino does not boot when SPI lines are loaded

I honestly can't imagine why a sketch like that would hang in this scenario. But I'm confident that my answer can solve the issue.
My guess is that the following happens:
The flash is selected (CS pulled low by atmega) at the moment at which the reset happens. At this moment, the master will stop generating a clock signal and CS will be floating.
Thus, the flash will not be deselected reliably due to the floating CS and MISO will remain in the state it was before the reset occured (HIGH if it was transmitting a logic 1, LOW for 0). Basically, the SPI communication of the flash will be stuck with MISO being actively pulled to logic high or low.
IDK why this causes the sketch to freeze, but if you add a pullup resistor to the flash's CS, it should be deactivated by default (and also after a reset of the atmega as pins will be inputs/floating by default). As a result, the flash can not actively pull MISO and should therefore barely affect the atmega at all.
I suggest you add the mentioned pullup and see if that makes any difference. If it doesn't I'm going to delete this answer, but it was a bit too long for a comment ;).
Edit: I also just saw that you are missing the pullup resistor on the reset pin. That could well be the actual problem.


In your setup section, you want to set or clear all relevant bits in admux.


Try to replace #define E1 3 with #define E1 PD3 and see if that helps.

The PBx, PCx and PDx designations are unambiguous, so using those are pretty much a safe bet.


How to send int[][] as a byte array through Serial

In the comment you write that the receiving end is an Arduino too. Then you can send the data in binary form.

To send the array:

Serial.write((byte*) arr, sizeof(arr));

(byte*) is cast of the memory location of arr to a byte array
sizeof returns the size of the array in bytes

To receive the binary data you must know the size. Here we read 100 16-bit integers:

Serial.readBytes((byte*) arr, 100 * sizeof(short));

Function readBytes is one of the 'timed' functions of Stream. It waits for the next byte (until timeout).

If one Arduino is 8-bit and the second is 32-bit, then use the type short instead of int, because the size of type int is different, but the type short is 16 bit long on all Arduinos.


Arduino Wifi Shield with monitor mode ( promiscuous mode )

Does it have to be a shield?

I would consider buying a cheap Wi-Fi router instead with good open-source support and a way to interface it to the Arduino. Their price is near to the price of Wi-Fi shields.

They consume little power, can be powered by 5V and have built in Wi-Fi.
Some have a built-in USB port, most have a serial port, which can be used to talk to the Arduino.
You would have to put custom firmware on it, plus the program which receives the raw packets for you.

Specifically, I would get a TP-Link TL-WR703ND for this task.

It can be fed 5 Volts, or 3.3 Volts with a little hacking
It has USB
It also has serial, and you can even hack an I2C port onto it
It can run OpenWRT

More info on this particular router


Switch case options get broken after a function call

You seemed to have solved it. For the reason, take a look at the compiler errors:
sketch_nov22a:31: error: jump to case label [-fpermissive]
       case 'M':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:38: error: jump to case label [-fpermissive]
       case 'W':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:43: error: jump to case label [-fpermissive]
       default:
       ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
exit status 1

If you got it to compile your compiler must be configured a bit differently to mine. However you can see that by putting int reading = ... in the case block, the compiler tries to execute that first (to initialize reading) which causes it to jump case labels.
By moving int reading outside the case statement, the compiler no longer has to initialize the variable, and that line merely becomes a function call and assignment (not a variable initialization).

You can avoid that by putting the code into its own block, that is, instead of:
  case 'E':

        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        break;

Use:
  case 'E':
        {
        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        }
        break;


As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.


Why can't I define the constant A0 (some pin) to something?

Because you have a ; at the end of your #define.

#define Uin A0;
analogRead(Uin);

becomes:

analogRead(A0;);

The Arduino website mentions this in their reference. For more in-depth detail about the C pre-processor you can read the (rather large) manual here.


Page 13 of 35 in the datasheet states:

  In order to provide access to any device or to assign an address to a
  SD before it is connected to the bus system, the communication must
  start with zero SA followed by low RWB bit. When this command is sent
  from the MD, the MLX90614 will always respond and will ignore the
  internal chip code information.

Supposedly, all you have to do is to connect only one device and use the address zero to read/write the registers.


Is this a good way to filter noise due to vibration in limit switch?

Hardware:

You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.

If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.

You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.

The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.

The ground path is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.

Software:

An integer can not be 0.9, therefor your filter does not work.

The function digitalRead() returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.

Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.

int digitalReadFiltered(int pin) {
  int result;
  const int n = 20;                // maximum 30
  int count = 0;                   // an integer can hold 30 analog samples

  for (int i = 0; i < n; i++) {
    if (digitalRead(pin) == HIGH) {
      count++;
    }
    delay(1);        // 1 ms for sampling during 20 ms with 20 samples
  }

  if (count > (n / 2)) {
    result = HIGH;   // counted enough HIGH values
  } else {
    result = LOW;
  }

  return(result);
}

In short, a pull down (or pull up) resistor with a low value makes the circuit low impedance, and the electrical noise will have less influence.

When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.

When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.

A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.

It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.

A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.


You can probably do a lot better than $17 but not much better than $8:

http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH_DefaultDomain_0&hash=item1e7ed94ffb

If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.


Here is the library for the Arduino IDE and a Raspberry Pi pico.
https://github.com/lrusak/Arduino-Core-Pico
Just install normally as a .zip.


As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is.  However, here are links to three instances of the same error:

• error: expected unqualified-id before 'if' on stackoverflow

• Arduino: error: expected unqualified-id before 'if' (using ping sensor), also on stackoverflow

• error: expected unqualified-id before 'if' on arduino.cc.

In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function.  You may have put some executable statements outside of loop() or setup(), etc.


Digital Potentiometer and Motor Speed Controller

The MCP42100 does not appear to be an appropriate digital pot for this application.

Without a schematic of the motor controller it is hard to tell, but a good guess would be that the digital pot is seeing voltages higher than the supply voltage you are feeding it, and higher than the maximum supply voltage of the digital pot (5.5V; 7.0V abs max). I don't see a voltage regulator on the motor controller board, nor would one be necessary for a low-end design. Probably just a PWM using a 555, as you say.

To make this work you probably need a different type of digital pot - one that can accept logic level inputs and has a higher supply voltage (12V + some margin). You also typically actually have to feed it the higher supply voltage (and be careful that nothing shorts and ruins the micro board).

Otherwise the input protection networks on the digital pot conducts more current than you would expect.


Is there a way to make a function take an exact number of clock cycles?

To the best of my knowledge, there is not. What you speak of is possible, but it must be done manually by counting cycles, and I suspect it wouldn't actually help you. (And then you get into CISC issues where instructions can take different amounts of time to execute, potentially depending on arguments. Arduino (the actual one) is kinda safe from that, but branch instructions still take multiple cycles, for instance. This says nothing about all the boards that work with, but aren't, Arduinos.)

There are two potential routes for this.

If this is for crypto, where you want to avoid side-channel attacks by detecting the length of an authentication or hashing function, it's not a good idea. Use a well-known library to do it instead, since in practicality it's not a good or safe idea to write your own (although if it's for a homemade door lock or safe lock, it's probably not a relevant issue since there are larger and more important security issues that will likely be found first despite your best efforts).
If, as I suspect, you simply want a piece of code to run at very precise time intervals, I suggest you look up something like the FreeRTOS port for Arduino. That will let you schedule a task to run preemptively so that it will always run at intervals. The BWOD sketch is still quite accurate, mind you, and below is a self-correcting version that compensates for any times that it might run a bit late (meaning that it should ALWAYS execute with millisecond precision, repeatably):

  unsigned long currentMillis = millis();//and you could always use micros()

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis += interval;//adjustment for additional accuracy

    //The task you want to run would go below:
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }

The caveat to your stated goal is that any microprocessor WILL NOT execute code exactly when you want. Arduino too is incapable of this, since even a blank sketch runs several interrupts that will take over the processor for short periods of time, causing your hypothetical sketch to be delayed. You HAVE to use a reference method like BWOD or a scheduler like FreeRTOS. These use a reference or set up their own interrupt to make sure that they run on time, with the only interrupts that could be an issue being the ones that run during that instance of the task.

What this means is that they have a bit of overhead to add spacing between tasks so that if one is delayed, it won't cause the next to run late. So do mind that you'll lose a quite small percentage of CPU time to your scheduler, but if that's really an issue, find a better board (like TI TIVA/Energia IDE).


The OP itself solve it:

  Ok - so I suspected that it was the Arduino at fault.. Turns out it's
  a cheap Chinese clone. After purchasing an official Micro, and wiring
  up the same component, I'm getting a nice clean signal (bar a small
  amount of acceptable noise), which is reflecting input tones
  accurately. Thanks again for all the input!


Weird behavior of variables when replacing for loops with if statement

You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.

define instead of

int y;

change to

long y;

and change

 void inOut(int &i){

to

void inOut(){

and remove

   return i;// Its a global var

change the line

unsigned long y = ((sensorValue*i)/600);

to

y = ((sensorValue*i)/600);

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay


Pins 0 and 1 on the Arduino Uno are used for serial communication with the computer over USB, including uploading sketches. If you connect anything to those pins you can interfere with the upload process.

To communicate between the two boards using serial communication without using pins 0 and 1 you can do software serial on other pins:
https://www.arduino.cc/en/Reference/SoftwareSerial


I suggest you visit the page Have I bricked my Arduino Uno? - whilst you have a Nano and not a Uno, it is the same processor and most of the remarks there will apply.

As the Arduino Nano page says:

  It has more or less the same functionality of the Arduino Duemilanove, but in a different package.

If you have another Uno or similar lying around you could conduct the "chip detector" test described on that page. You could also perform the loopback test.

It is possible on the FTDI chip (underneath) is damaged in which case there would be alternatives to using that.


Help Understanding FFT Analysis and analogRead()?

Nick Gammon already gave a very fine answer about the meaning of the
mysterious numbers you were wondering about. Here I am trying to answer
only your last question:

  why manipulate these directly in the first place, because if you
  reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher
sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @
16 MHz), the Arduino core normally configures the ADC prescaler to 128.
This gives a conversion time of 104 µs (equal to 13 × prescaler ÷
F_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for
telephone quality audio, but insufficient for hi-fi applications. This
example code sets the prescaler to 32 for a conversion time of 26 µs and
a maximum sample rate around 38 kHz. According to Atmel, the ADC should
work fine with this kind of sample rate, except that you should not
expect to get the full resolution.

The main reason, however, is not to get a fast sample rate, but rather
to get a consistent sample rate. The problem with analogRead() is
that it is a blocking function. If you look at its source code you
will see a busy wait like this:

// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));

This means that the CPU is not doing anything useful while waiting for
the ADC to finish the conversion. If you do analogRead() in a loop,
the CPU will wait for the ADC, then the ADC will be idle while the CPU
completes the loop and so on. The conversion period is then the time
required by the ADC plus the time taken by the CPU to loop. And the
CPU time is hard to predict because it can be influenced by interrupts
and by conditional branches inside the loop.

This code, in contrast, configures the ADC to work in free running
mode. In this mode, the ADC starts a new conversion as soon as the
previous one is done. This way you get a steady sample rate while the
ADC and the CPU work in parallel. In the loop you see these lines:

while(!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc

The comments are a bit misleading. The first line (which I would rather
write loop_until_bit_is_set(ADCSRA, ADIF);) waits for a flags that is
set when the current conversion is done and the data register updated.
The next line does not restart the ADC (it restarted itself, as it is in
free running mode): it only clears the flag so that it can be
meaningfully tested on the next iteration.

Now, I have a few comments on this code that are not directly related to
your question, but may be useful if you are going to build your program
on this basis.

First, it should be noticed that the whole ADC-reading loop is done with
interrupts disabled. This is not normally needed, as the free running
mode gives you a steady sampling even if the CPU timing is somewhat
jittery. The only valid reason I see for disabling interrupts is if
one of your ISRs takes so long to execute that you may miss one sample.
This could very well be the case with such a high sampling frequency.
But still, there is no point in keeping the interrupts disabled during
the FFT processing. And there is no point in turning off Timer 0 if you
are disabling interrupts anyway.

My second point is about the three lines starting with byte m = ADCL;.
Those are meant to read the ADC data register in the proper order: low
byte first. However, the C compiler is well aware of the proper way to
do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the
datasheet chapter about Timer 1). Thus, these three lines can be
simplified to just int k = ADC;.

My last point is that having the CPU left adjust the result (k <<= 6)
takes some time, as it is implemented as a loop. There is no point in
doing this when the ADC can do it for free: you just have to set the
ADLAR bit when configuring ADMUX in setup(). Then the 5 lines starting
with byte m = ADCL; would be reduced to

int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int


Matrix keyboard and 7segment display countdown combination

Try using millis(), it returns the number of milliseconds passed since the Arduino board began running the current program.

When you start the countdown you set a variable for a beginning time

int millisBegin = millis(); //put this at the end of your setup() {}.

You will also need a "border" to know when one second is over, so

int millisBorder = 1000; //one second border

Every time your the loop() {} starts over you can check if one second has passed so far

int millisNow = millis();
if(millisNow - millisBegin >= millisBorder){} //if one second over, do {}

Now I would work on the segment showing thingy. In the {} I would put a new variable, let's call it counter = 4; //4 because I found 3 numbers in your sketch. Every time the if() {} is being executed, you go through more if () {} statements, checking what number to display next.

if (counter == 3)
{
  //show number 3
}

if (counter == 2)
{
  //show number 2
}

if (counter == 1)
{
  //show number 1
}

if (counter == 0)
{
  //show number 0
}
counter = counter - 1;

At the end we take one off the counter, so the next time we enter the if(one second over) the number displayed will get lower

And well now there are multiple ways of doing the keyboard thingy. You can keep checking if there is a key available, and if so you can safe it as a String (most people hate strings, but I never had a problem with them to be honest).

After you've saved the key as a String you can use the strcmp(); method to compare the string with the solution/answer strcmp(key,answer);. If the key and the answer are the same, it will return 1.

if(strcmp(key,answer) == 1)
{
  Serial.println("you made it");
}


Distance sensor - Not working on fabric surface

There are three types of commercially viable sensors for small scale projects:

Ultrasonic sensors(HC-SO04 and similar): These sensors use ultrasound much like a submarine uses its sonar to locate things by sending out a sound wave(trigger pin) and then measuring the time it takes for the sound wave to bounce back by reading the echo.There are two problems with this sensor. It needs a pretty solid object to bounce sound of thus walls are good but cloth absorbs the sound wave and the echo never bounces back. The second is you can encounter ghost echos when the sound wave strikes a corner and creates a echo for an object that is not really there. These sensors typically have a range of around 250cm to 600cm however some sensors can sense up to 7 meters away. Thus while it has good range it can not reliably detect all things and you might have false positives on it as well.
IR(Infrared) Sensors: These work like the ultrasonic ones but with light instead of sound. The sensor sends out a pulse/beam of IR light and measures the time it takes to reflect the light pulse/beam. This sensor is much faster than the ultrasonic ones but they have a much smaller range than ultrasonic sensors with a normal range of about 1.5 meters. While they work on most obstacles some might be missed due to the ability of some materials to absorb the IR light pulse thus there is no echo to measure.
LIDAR(Laser Range Sensors): There are various models of these but the principle is the same as the IR sensor. These can have massive range but they also come in at a massive prices. You can find cheaper ones around I saw a model for $80 that has a 40 meter range.


Is 1MB flash enough for OTA upload in ESP-01?

Yes, 1MB is fine for OTA. There are, though, a few caveats when working with OTA that you must observe regardless of the flash size:

The maximum OTA program size is less than half the available flash size. Typically it is about 500kB. Two copies need to be stored in flash, plus the partition table and NVRAM. The rest of the flash on larger chips is most often dedicated to FS storage.
The device must first be programmed through USB with an OTA-compatible partition layout.
After programming through USB it must be manually reset or power cycled to set the boot mode correctly.
You can not change the partition layout over OTA programming. You need to make sure you have the same partition layout selected as when you originally programmed through USB.
ArduinoOTA.handle(); has to be called very regularly to handle the programming request. You can't have any blocking code in your sketch that might stop that from being called.

Observe all those and you should be able to program over WiFi with no problems.


Problem with power supply ws2812b Arduino 5v vs 12v

The regulator on an Arduino is likely analog.  On this Arduino Uno the regulator is an analog NCP1117ST50T3G as seen in this schematic.  On page 2 of the NCP1117ST50T3G spcification it is stated:

  Internal thermal shutdown protection limits the die temperature to
  approximately 175°C. Proper heatsinking is required to prevent
  activation.

Being an analog power regulator, the difference between the input voltage and the regulated output voltage eventually turns into heat.  This may explain why a 9 volt source may work (drop is only 9V - 5V = 4V) while a 12 volt source may not work (drop is 12V - 5V = 7V).

Consider using a 5 volt power source avoiding the Arduino analog power regulator.  Or, if the only source is 12 volts (for example an automobile), consider using an external switching or buck power supply to convert the 12 volt down to 5 volts and again avoiding the Arduino analog power regulator.  Lastly, it should be possible to still power the Arduino with 12 volts and use its internal power regulator to only power the Arduino. Then independently power the LED strip using an external power regulator.  This last option will likely have the benefit of eliminating the capacitor bank seen in the question and associated components.


TinyExpr does what you want, and more.

TinyExpr is a very small recursive descent parser and evaluation engine for math expressions. It's handy when you want to add the ability to evaluation math expressions at runtime without adding a bunch of cruft to you project.
In addition to the standard math operators and precedence, TinyExpr also supports the standard C math functions and runtime binding of variables.

Your example
You'd just need to save tinyexpr.h and tinyexpr.c next to your Sketch.
#include "tinyexpr.h"

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

void loop() {
  char term[] = "12 + (2 * 5)";
  Serial.println(term);
  int error;
  double result = te_interp(term, &error);
  if (error){
    Serial.println("Problem with expression.");
  } else {
    Serial.printf(" = %.10g\n", result);
  }
  delay(1000);
}

It outputs:
12 + (2 * 5)
 = 22

Since term is known at compile-time, this example is not very useful, and it simply outputs 22 in an endless loop.
Basic interactive console
If you use the input from Serial, you can write a very basic interactive console. A String has been used for conciseness, but this example could be rewritten with cstrings:
#include "tinyexpr.h"

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

void loop() {
  if (Serial.available() > 0) {
    String expression = Serial.readStringUntil('\n');
    Serial.print("> ");
    Serial.println(expression);

    int error;
    double result = te_interp(expression.c_str(), &error);

    if (error) {
      Serial.print(" ");
      for (int i = 0; i < error; i++) {
        Serial.print(" ");
      }
      Serial.println("↑");
      Serial.println("I didn't understand this part.");
    } else {
      Serial.printf(" = %.10g\n", result);
    }
  }

  delay(50);
}

TinyExpr knows the order of operations, and it understands many other mathematical expressions:
> 12 + 2 * 5
 = 22
> 3^5
 = 243
> exp(7)
 = 1096.633158
> (1 + sqrt(5)) / 2
 = 1.618033989
> 1 + 2 * 3 + 4 * 5
 = 27
> sin(pi/2)
 = 1
> sin(pi/3)
 = 0.8660254038

If there's a syntax error somewhere, error tells you the position of the first encountered error:
> 3 +
      ↑
I didn't understand this part.
> sin() * 5
      ↑
I didn't understand this part.
> 3 / (4 + 5 * 7
                ↑
I didn't understand this part.


What is the advantage of a 3MP OV3660 sensor on the ESP32 M5Stack camera if it can only save upto 2MP images?

The limit isn't the camera - it's the memory.
At 3 megapixels you have 3145728 pixels. At 3 bytes per pixel (8 bits each of red green and blue) it requires 9437184 bytes to store the image. That's more than can fit into the 8MB PSRAM.
1600x1200 will probably be one of the standard resolutions that the specific camera in use can capture, and is probably the biggest size that is below 8MB in size for a single frame.
So, what advantage of having a 3 megapixel camera? Well, none to you, other than the cost. It's probably cheaper to use a newer 3 megapixel camera than an older 2 megapixel camera.

It is perfectly possible to run at the resolutions you desire though. This resolution is known as QXGA and is supported by the OV3660 driver in the ESP32 Camera library.  There are some caveats though:

You must use JPEG compression. Not only is this to make the image small enough to fit into PSRAM but also to make it possible to write the whole frame into PSRAM fast enough that you don't miss bits of the data.
You will not be able to "do" anything with the image other than send it to somewhere else (such as an SD card or a web server). There just isn't enough room to uncompress the image.


Arduino Leonardo on Win 8.1 COM port disappeared

Strange, it's resolved itself/I resolved it. I don't know whether what I did was actually responsible for solving this but I'm back in business:
* I reset the board so that the bootloader appeared as a com port
* I set the arduino IDE to use the port that appeared for the bootloader
* I uploaded a simple sketch and pressed reset during the "upload phase" so that the port appeared during the upload
* the upload completed successfully and the arduino was back in the com port list

I'd still be interested to understand what I did that caused the problem in the first place but I suppose something was corrupted on the board?


Why PIN3 stays at 1v3 in a IR emitter project?

A few things. As somebody else suggested, try a normal red LED and make sure that works first.

Note that your resistor is allowing too much current through the LED. A high-current LED might tolerate 20 mA (thousandths of an amp.) With a 47 ohm resistor, you're pumping 5/47, or about 106 mA into the LED, which is likely more than 5 times what it is designed to handle. You will quickly burn out your LED. You should use a 270 ohm resistor instead.

Also try just setting pin 3 to an output with this line:

pinMode(3, OUTPUT);

And then manually setting that pin to on:

digitalWrite(3, 1);

If the LED lights up, you know the pin is working correctly. Then use the code you posted with the same setup, and make sure your LED flashes. If THAT works, try putting your IR LED back in the circuit.


I found a fix, it's not elegant or easy to use, but it works.

Steps to take

-Install a fresh version of teensyduino

-Make a copy of [arduino directory]/hardware/tools and save it anywhere as a backup (sometimes weird, buggy things happen)

-Make a copy of teensy.exe from the tools folder, and put it in the same directory as arduino.exe

-every time you run arduino.exe (don't double-click on a .ino file), first start teensy.exe and everything should work.

Sometimes, the tools directory gets deleted (It just seems a bit buggy), if that happens copy the backup and paste it where it should be ([arduino directory]/hardware/tools)

Also occasionally teensy.exe gets deleted, so make sure to have a backup of that as well.


The WiFiClient.h header and WifiClient.cpp source files are useful for reference.

  Is the best data structure a linked list?

Probably not here.  Possibly not ever.  It's a load of effort to implement, and won't give you any benefit.  Just create an array of them:

WiFiClient clients[5];

Then perhaps something like

WiFiClient newClient = server.available();
if (newClient) {
    // TODO: Check whether we have an existing connection from this IP
    // TODO: Get the first 'free' array index
    clients[firstFree] = newClient;
}

  How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles?

Get the remote IP address of the new client

IPAddress = newClient.remoteIP();

Do the same with all the connected clients in your array* and compare them.  If you find a match, drop the connection

newClient.disconnect();

and, probably, don't put it in the array.

  How can I detect when they disconnect in order to delete them?

if (client[i].connected())

Lastly, how do we keep track of which items in our array are current active connections, and which aren't (either not yet used, or already disconnected).  You could do this several ways.  One would be to iterate through the array, checking whether the item is valid and connected:

// Returns -1 if no free slots
int firstFree() {
    for(int i=0 ; i<5 ; ++i) {
        if(!clients[i] || !clients[i].connected()) return i;
    }
    return -1;
}

All code untested so you may find typos, but I believe it's basically correct.


Trying to get my mega 2560 to work for my 3d printer

COM4 ... assuming it's a windows host, then?

All those errors may be because the COM port specified doesn't exist. (changed and/or not seen)

0.) Has this mega ever had a sketch uploaded successfully before this? (for anything)

1.) Have you verified within the arduino IDE that COM4 is showing up in the ports menu?  (Tools => Ports)

2.) Did you plug the arduino into a different USB port?  (sometimes when it's re-recognized it'll assign a different COM port)

If it's changed COM port, then (obviously) change the port designation in the IDE.

Try switching it to a different USB port and waiting for device manager to recognize it.  If that doesn't work and the mega worked before update the question with the above info and we'll try again.


Is it better to use c_str or toCharArray?

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely c_str() is better. Though, what I see even more often is the use of character arrays char* strings instead of String (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like xpcc trying to make a real and smart use of the C++ abilities in the embedded world.


ESP8266 reseted due to relay / AC plugged

Try add some power filter like this:

Between the breadboard and ESP board.


Controlling 2WD car chassis with PS3 controller

I found three issues:

You don't have a # before the include on line 1.
There is no } at the end of the void loop().
You forgot to include an if statement for when the joystick is idle.

Try this code:

#include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
                  //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
    Serial.begin(115200);
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
    }
    Serial.print(F("\r\nPS3 USB Library Started"));
    pinMode(motora1, OUTPUT);
    pinMode(motora2, OUTPUT);
    pinMode(motoraspeed, OUTPUT);
    pinMode(motorb1, OUTPUT);
    pinMode(motorb2, OUTPUT);
    pinMode(motorbspeed, OUTPUT);
    delay(5000);
}

void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
        } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 255);
        } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 200);
        } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 200);
        } else { //stop moving
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 0);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 0);
        }
    }
}


Simple Script controlled by Raspberry not working

Finally I've found the error, it was the serial communication baud rate: 115200. It seems that at higher speeds it not works properly, lowering it to 9600 do the trick.


How do I create a state machine for my purpose?

Creating a few boolian variables could help with this.

bool opening = 0
bool closing = 0

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
    opening == 1  //variable "opening" is set to on
    closing == 0  //variable "closing" is set to off
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW);
  }
    else if (buttonState == Low && closing == 0){ //variable "closing" is tested
      opening == 0    //variable "opening" is set to off
      closing == 1    //variable "closing" is set to on
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, HIGH);
      delay(4000);
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, LOW); //Same issue  here
  }
  delay(1000) // delay is in milliseconds. So 1000 = 1 second
}

These new variables are set when the code is ran the first time. Therefore, no looping.


State change in Arduino Using Adafruit display

You should use a switch statement ... than after the switch statement you get the in between states:

// conditional loop
{

    // prepare for switch (if something is needed)

    switch (menustate)
    {
        case 1310:
            menustate ++;
            Serial.println("Execution:");Serial.println(menustate);
            break;
        case 1311:
            menustate ++;
            if (hr==0)
                 menustate ++;
            else
            {
                aCount++;
                gpArray[aCount]=hr;
            }
            Serial.println("Execution GP:");Serial.println(menustate);
        break;

        case 1312:
            // ...

        default:
            // You can do here things with all other values
    }

    // Here you have the in between states available
}

You should put this switch statement in some conditional loop (like until an end state is reached.


How to restart a counter in a program using a push button in a LDR Tripwire setup

Try out this code. I made some modification and also comment out that things.

#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 6, 5, 4, 3);

int laser = 8;
int pushbutton = 12;
int flag = 0;
int myCounter = 0;

void setup()
{
  pinMode(laser,OUTPUT);
  pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

  lcd.begin(16, 2);
  lcd.print("Person Counter:");
  lcd.setCursor(0,1);
  lcd.print(0);
}

void loop()
{
  lcd.setCursor(0, 1);
  digitalWrite(laser,HIGH);

  if(analogRead(A0) < 600) //A0= LDR
  {
    flag = 1;
  }

  if(analogRead(A0) > 600 && flag == 1)
  {
    myCounter++;
    delay(200);
    lcd.print(myCounter);
    delay(20);
    flag = 0;
  }

  if(digitalRead(pushbutton) == LOW) // When button pressed
  {
    myCounter = 0; // Set counter to 0
  }
}


My push button code doesn't work properly

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

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


Ultrasonic sensors with 12v motors will not work! (ADRUINO)

TLDR: change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

You are using pins 7 and 8 for ultrasound.

At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5
You will see, that the shield is using pin 7 as M2INA and pin 8 as M2PINB

So each loop you push M2INA (trigPin) LOW, then HIGH then LOW, then wait until the sensor write HIGH to M2INB (echoPin) just to immediately send PWM pulses to both trigPin (M2INA) and echoPin (M2INB) via commands

    md.setM1Speed(100);
    md.setM2Speed(-100);

No way it can work as you expect.

You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare

#define trigPin 3
#define echoPin 5

and connect your ultrasound sensor there acordingly.

(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").

Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.


Yes. Arduino has two buffers. See the HardwareSerial.h and HardwareSerial.cpp


You cannot upload the bootloader through the ATmega's UART pins.

Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.

Otherwise you may just have to desolder the chip.

A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.


You can retrieve the program currently in your Arduino with the
avrdude tool. This tool comes with the Arduino installation. The way
to call it is somewhat OS-dependent. On Ubuntu, for an Arduino Uno, I
type:

avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:r:prog.hex:i

This creates the file prog.hex with your program in Intel
HEX format. You can save this
file if you want to re-install it on the Arduino later. You can also
turn this file into an assembly listing with avr-objdump:

avr-objdump -m avr -Dz prog.hex > prog.lst

You may be able to make some sense of this listing if

you are well versed in AVR assembly language
you have lots of spare time

As others have said, you cannot expect to get the original C++ source
back.


C Serial Communication Code is unreliable

I recommend you change the type of incomingByte to int, like was advised in the comments. Also, your null-termination is occurring past the end of buf; change the condition in the while statement to i < buf_max - 1, so that one byte is left for the null. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.