Can we use ESP32 to program ESP32-CAM through ESP-IDF

All you need to program any ESP32 (Cam or not) is a serial interface.  How you make that serial interface is up to you.

Most ESP32 development boards have a USB to UART converter on them which you can use just like on an Arduino - keep the ESP32 you're using for the programming in RESET so it doesn't try and respond on the UART.

You could also program the "programmer" ESP32 as a UART passthrough to connect the USB UART through to the other UART so you don't need to mess with holding in RESET.


Following @dandavis's advice. I will connect the switch between the power source and the board, get rid of the LED, and use ESPNOW for communication! Thanks for the help.


I have four servos connected to an arduiono uno and I cannot control them

As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption.  When you move a servo the power consumption rises considerably.  A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.

If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.


Triggering Sound - Arduino + Contact Mic

I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much.
It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier,  but if you're using little ones like 8ohm 0.25W with the music shield will be enough

some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground


You can use the macro __FILE__ to get the filename that is being compiled.  That may not be your INO file, but may be some derivative of it.

Serial.println(__FILE__);

You also get some other handy macros:

__DATE__
The date the sketch was compiled

__TIME__
The time the sketch was compiled

__LINE__
The line number where __LINE__ is being used

The combination of __FILE__ and __LINE__ is commonly used for debugging:

Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);


Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.

If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.

Untested:

#include <avr/interrupt.h>

void setup(void)
{
  cli();
  DDRB |= _BV(PB2); // Configure OC1B as output
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
  TCNT1 = 0; // Initialize timer count
  OCR1A = 0xffff; // Reset the timer at this count
  OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
  ICR1 = 0xff00; // Set to an invalid initial value
  TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
  TCCR1B = _BV(ICES1); // Capture on leading edge
  TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
  TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
  TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
  sei();
  TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
}

ISR(TIMER1_CAPT_vect)
{
  TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
  PORTB &= ~_BV(PB2); // Kill the charging output
  // Check ICR1 for the captured value
}

ISR(TIMER1_COMPB_vect)
{
  if (ICR1 == 0xff00)
  {
    // WELL CRAP, charging is taking too long
    // Maybe try with a slower clock?
  }
}

void loop()
{
  // Do other stuff
}


There's two basic ways of doing it.

Send a byte from the master to the slave first to select which sensor you want, then request the data for the currently selected sensor, or
Request lots of bytes from the slave and fill them in one at a time as the requests arrive.

The first way is the slow, but "I2C" way of doing it - basically each sensor is its own register in the slave, and you select which register you want to read from.

The second way is faster, but you have to keep track internally of where you are.

A good compromise is to implement "auto increment" which does both scenarios: if you send a byte it sets the current sensor to read from. Then each read returns the current sensor and increments the sensor number internally in the slave, so the next read will get the next sensor.

That way you have a way to "reset" the sensor index that you are reading from, and it's reasonably quick to get all the sensors, since you just need to do multiple reads after a single write.


Arduino outputs garbage values on serial monitor with ESP8266

As noted by Matt, the baud rate for the ESP8266 can vary depending on the firmware version/manufacturer.  9600 and 115200 are the most common.  If you can connect using a serial terminal program (like CoolTerm) you can then test the baudrate.

It sounds like the ESP8266 is set to 115200, but in my experience (and others') SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting). Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  But you can reset this and see what the max reliable value is for you in your configuration.

How to change the baud rate on the ESP8266 will depend on the firmware version. I've had success with AT+IPR=9600. You only need to run this command once (it's a persistent setting). I'd suggest, based on your description, that this is the most likely culprit that's causing the intermittent "garbage" output you describe.


Arduino SDFat Libray overwrites last value

You just need to open the file in APPEND mode:

SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

  O_APPEND

  The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by reference so it doesn't keep creating new copies of the internal structure:

bool SDClass::SetLine(SdFile &Cache,int target, int reference)


Arduino will not recognise USB ports on my Mac running Sierra

I spoke to a very clever friend who has had similar problems. The answer lay in downloading the FTDI helper package not just the driver.  If anyone else is having a similar problem the website is

https://www.ftdichip.com/Drivers/D2XX/MacOSX/D2xxHelper_v2.0.0.pkg

I downloaded it and now my lilypad and USB port is recognised by the Arduino software.

Just in time for Thursday.

Thanks to all who tried to help.

K


Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266

Is it possible to get the same kind of serial communication over WIFI?

Not precisely, no - but TCP sockets are a similar concept.

You would be best programming the ESP8266 directly to implement a simple TCP to UART bridge firmware instead of fighting with the crummy AT firmware that comes with them.


Multiplication operator with or without braces

The parentheses should definitely make no difference. My guess is that
what you saw was just a coincidence. The analog ranges you have defined
are extremely narrow. Any instability in the circuit can throw your
readings out of the expected ranges. If you get a reading that does not
fit in any of those ranges, none of the if conditions will evaluate to
true, and you end up with the result being zero, as this is how you
initialized the variable ans.

I suggest two changes to your program:

Make the ranges wider
Repeatedly read the analog input until you get a valid reading.

To illustrate the second item, here is a code snippet that splits the
logic of you if chain in two parts: first read the operator
(repeatedly until we get a valid reading), then perform the operation:

// Read the operator.
char op = ' ';  // space = no operator read so far
do {
    int val = analogRead(A0);
    if (val == 0) op = '+';
    if (val >= 97 && val <= 98) op = '*';
    if (val >= 253 && val <= 254) op = '/';
    if (val >= 407 && val <= 408) op = '-';
} while (op == ' ');

// Perform the operation.
switch (op) {
    case '+': ans = num1 + num2; break;
    case '*': ans = num1 * num2; break;
    case '/': ans = num1 / num2; break;
    case '-': ans = num1 - num2; break;
}


Can an Arduino access a network database?

The M0 has a "native" USB interface. Because of that it can be programmed to appear as any kind of device you can image - as long as you can find (or write) the code to do that.
You could (though I have never tried and don't know what code is readily available for this) program the USB interface to be a USB Ethernet device. Your computer would then see it as a new Ethernet interface.
It would then be trivial to "share" your internet connection in Windows with that new Ethernet interface (nothing to install, but settings on the computer need changing), and your Arduino would then be on the network the same as your computer (just as if you'd given it a WiFi interface or something like that). Then it can connect to the database itself (or to a website that communicates with the database if that is simpler) and do whatever it needs to do.
Step one, of course, will be to find a library that will give you that USB Ethernet interface...
A much simpler option, if you're willing to change your M0 for something else, is to use a chip with a built in WiFi interface, such as the ESP32. There's no need for your computer at all then.


Powering two stepper motors with A4988 drivers

Both power supplies are suitable.

The actual 12V/24V current required is not comparable to what the driver current is set at, since the stepper motor coils do not have those 12V/24V across them.

My first 3D printer came with a 12V 5A power supply, which proved suitable for simultaneous use of four stepper drivers, the control board, a display, and the heater cartridge (40W).


Can I control solid state relay directly from arduino digital pin?

According to the datasheet there are multiple models.
Some already have an input resistor for the led (in the opto-isolator) inside the package, but some don't. For the ones that don't have a resistor inside, you'd need to add one yourself, to limit the current to around 10mA.
Some models also have a snubber circuit inside the package. The need for this depends on what kind of load is connected (inductive vs. resistive (AFAIK)).
I thinks the green thing, in the picture, is a fuse. On the other side of the SSR you can see and indicator led, transistor, and 3 resistor (one to limit current to the SSR, one to limit the current through the indicator led, and on for the base of the transistor.). They probably use a transistor, because the current for the SSR and the indicator led combined, is to high for certain micro controllers.


Unable to get Arduino Ethernet Shield IP address connected to Raspberry

192.168.10.0 is not a valid IP address (unless it's on a /32 subnet which makes no sense on ethernet).

You need to allocate a proper IP address within a proper subnet, such as 192.168.10.1/24 (i.e., IP 192.168.10.1 and netmask 255.255.255.0), and either manually provide a similar IP address to the Arduino (such as 192.168.10.2/24 [IP 192.168.10.2 netmask 255.255.255.0]), or install and configure a DHCP server on the Raspberry to hand out IP addresses within that subnet range (e.g., 192.168.10.100/24 to 192.168.10.200/24) for the Arduino to then be able to use DHCP mode.

Most of that is outside the scope of an Arduino SE site, though.


Can I get a Datetime object from a unix timestamp?

The seconds since (UNIX) epoch relies on a database.

  New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

Reduce the timezone database to the timezone you are actually interested in;
Don't forget about daylight savings time for you specific timezone;
The leap years are well known too and reasonably easy to program;
The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

Conclusion

So can you convert epoch to a time/date format? Yes.
Will it be accurate? It'll drift away over time (months or years)

Advise

If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?


Generating a 38 KHz signal without timers

A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz.  That is 1/76,000 = 0.000013158s, or 13.158µs.  That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.

I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz.  So fairly close.

So now you need to create a tight loop that is exactly 105 clock cycles long including the toggling of the IO pin and the comparisons and branches for the loop.  For that you need to do some careful instruction cycle counting and work in assembly language.  Page 268 of the data sheet details the clock cycles used for each instruction.

The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks).  That is then a grand total of 210 clock cycles, or 1/(210*0.000000125) = 38.095kHz.

You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.

However all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause jitter in your output as the interrupt routine is being run instead of your IO pin driving loop.

If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the micros() function to find when 13µs have elapsed and do it all in C instead of assembly.  You will still need high speed direct port access rather than using digitalWrite() since digitalWrite() adds way too much overhead to be able to do that kind of timing reliably.  Something like:

uint32_t start = micros();
while(1) {
    if (micros() - start >= 13) {
        start = micros();
        PORTB ^= 1<<4; // toggle B4
    }
}

Note the use of while (1) there rather than relying on the loop() function repeating itself.  There is quite a large overhead in using the auto-repeating of loop() that can be avoided by looping within it with a while (1) like that.  Of course, anything else you want to happen repeatedly would have to be inside that while loop, and most likely would impact your output timing somewhat.

So a much better solution would be to use a timer, since that is what they are there for.  But fidding with timers breaks things like millis() and delay().  So the answer to that is don't use millis() and delay().  Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own.  If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed.  When that count exceeds 1000 you subtract 1000 (don't zero it) and add 1 to a millisecond counter.  Now you have the equivalent to millis() in a global (remember to make it volatile) variable that you can use instead of millis().


Should millis() be stored in a variable once each loop, or called for every reference?

The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.

Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.

Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between currentMillis and previousMillis is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since currentMillis appears twice in the loop.

As far as memory goes, an unsigned long uses very little.


Problems using an arduino with vex motors and motor controller 29

VEX motors with Servo library have the following functionality:

0 one direction (full speed)

90 stop

180 opposite direction (full speed)

So at 90, it is trying to remain motionless and hence creating that sound.

btw. You should provide power to motors separately from the Arduino. You might fry your Arduino if you run VEX motors from it. Best solution is to power using 7.2V 3000mAh Flat NiMH High Power Battery Packs.


How can I create a power rail on my Arduino shield?

Just bridge them.  Wire in your +5V connections then join them together on the back with lots of solder.  Maybe with a strand of 0.6mm single core wire along it for extra ruggedness.


Do I need the Motor Shield to drive servo motors?

The Motor Shield is for driving bare motors, not servos. Servos already include drive electronics and only require a PWM signal in order to control them, whereas the Motor Shield provides the drive electronics for bare motors.


How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?

Yo can use the keyboardReport() function to send key-codes with modifiers. Here is an example that will send an ! by sending the keycode for 1 plus a shift key modifier...

    // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
    // press the keys consecutively,. it presses them simultainiously.

    // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

    uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
    blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

    // This release seems to be required. Without it, the last pressed key just repeats forever.
    blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188

...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212

Unfortunately the hid_keycodes example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...

https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928


Arduino ADK, other board, shield or what?

You would need a USB host shield to achieve what you want.

The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:

http://www.arduino.cc/en/Main/ArduinoUSBHostShield

In the list of supported devices is:

USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.


Yes, depending on the current that will flow.

If your PWM output pin is connected to 5V without a current limiting resistor, nothing will happen during the HIGH phases of the PWM, but you will short the input pin during the LOW phases.

According to the manual of your motor controller, you should be able to use a current limiting resistor to prevent this.
Since the ATMega328P on your Arduino Nano can sink a maximum of 40 mA, that resistor should be at least 125 Ohms. A resistor larger than 1 kOhm should work fine.

The other option would be installing a diode between your Arduino Nano and the motor controller.
This does not require the use of a current limiting resistor.
The motor controller would still work, since the minimal voltage for the pin state to be detected as HIGH is 3V (1), much lower than the ~4.3V you're left with after a diode.


Newbie need help to make a motor run for a laser scanner and some questions

A servo motor would have a lot more control than a normal motor. You usually command them to go to one of the predefined steps (stops) by using a function call in the servo motor library.
You can run independently of the computer. Many people do this. Certainly you can run off a battery. It doesn't have an ON button, you normally would have this between your battery and the Uno (eg. built into the battery pack). Like this:

A 9 V battery? I wouldn't use one, especially to drive a motor. It won't last long. Get something like 3 x AA batteries in a battery holder.

To show you the idea, I have this servo motor (SG-5010) I got from Adafruit.

I measured it using about 200 mA of power when operating. Now, I looked up a typical Alkaline 9 V battery, and found that, consuming 200 mA, it lasts for around 400 mAh. Thus, you could say it would be good for two hours at that rate. Plus, the Arduino will take around 50 mA, so maybe less than two hours.

A smallish servo motor won't need a motor shield. The pictures on the linked page show ordinary brushed motors. A servo motor has 3 leads:

Power (eg. 5 V)
Gnd
Data

Make sure you connect the grounds together, but the power could go to a separate power pack. A bit depends on how much power your motor will use. The data goes to the Arduino for the information about which rotation point to step to.

You should be able, in code, to change the rotation position, forwards and backwards.


Using Multiple Serial Ports with arduino nano

You can use SoftwareSerial library in order to instantiate a second (soft) serial port.

By looking at the example, it seems that you can use any two digital pins to use SoftwareSerial library and instantiate a second serial port along with the hardware serial port.


How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?

Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.

int lastValue = 0;

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  lastValue = value1;
  delay(10);


Arduino controlled LCD 16x2 is very very dim

I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).

It will light up when the backlight is correctly connected, which is impossible to tell from your photo.


Is it possible to build a 1080p OSD webcam shield?

None of the ATmega based boards have the hardware (in terms of acting as a USB host) or power (in terms of handling probably compressed 1080p video).

Potentially one of the ARM boards could do this. The Arduino Due can act as a host, but it sounds fairly experimental, and none of them will have drivers to connect to the camera.

If a shield was developed to do this, it would have so much more power than the Arduino that the Arduino would probably better be viewed as a slave to the other device.


Sending a double message for action to occur

I do not have and ethernet shield at this moment to test on it your code but hopefully the next observations will help to solve your issue.

  If I send the command again, the Arduino does not turn on the LED,
  unless the command was send twice, consecutively.

It seems that your string is not correctly processed, probably caused by "garbage" from previous received string or incomplete string. I think is from this part of the code

 if (client.available() > 0) {
  char thisChar = client.read();
  command += thisChar;
  ProcessCMD( command );

You are trying to append a char (one byte) to your command string; by doing this you are not getting the received string necessarily because the "+=" is for retrieve char by char (for example, inside a while loop). First try to print thisChar variable to ensure what are you getting and also you can print client.available() to see how many bytes you got.

Second, for your ProcessCMD function it could be better to use pointers to handle the command variable, meanwhile you must clean command variable always (and not only when CMD.lenght > 11 ), i.e,

if(CMD.length() > 11){
  command = String("");
}

must be at the end of the ProcessCMD function

  command = String("");

Also you can ensure that when you set UP=true, also set DOWN=false and so on. I prefer the Switch-Case structure to handle commands.

Try to follow arduino examples to better understand.

Cheers.


For the situation illustrated in the question – displaying data – polymorphic functions already exist, and might as well be used in this case.  Specifically, use the Streaming.h contributed library.  It adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it via Streaming5.zip from arduiniana.org .

In other cases, a union data structure allows treating an area of memory different ways.  Wikipedia's Union type article explains the general idea.  See eg tutorialspoint.com/cprogramming for union syntax and usage.  For some reason, arduino.cc's Language Reference page hasn't got union on its list of language features.  However, mcgurrin.com has a page called There is Power in a Union that codes a simple Arduino C example two ways (where bearing is an int):

higherByte = compass.read();
lowerByte = compass.read();
bearing = ((higherByte<<8)+lowerByte)/10

-vs-

union Data {
  byte b[2];
  int value;
};
...
union Data data;
data.b[0] = compass.read();
data.b[1] = compass.read();
bearing = data.value/10;


The first being the code first returns "hat is empty" before the
  numbers.

Well, you have to comment out the line

Serial.print(" hat is empty ");

  I would like define the randomHatEndNum automatic by the lenght of my
  custom array,

To get the size of an array, the standard idiom is

const int numberInHat = sizeof(things) / sizeof(things[0]);

I rewrote your sketch.

The idea is use randArray to store all the remaining values to return. Then, randomly pick one value (to return) and replace randArray with -1, which signal that the value has been returned, so don't return it again.

The best for functions returning random values is always work in the range 0..n, and adjust that value in the calling code if you need some other range (like 1..n+1). It's simplier and simplify debugging.

/* RandomHat
  Paul Badger 2007 - updated for Teensy compile 2017
  choose one from a hat of n consecutive choices each time through loop
  Choose each number exactly once before reseting and choosing again
*/

char *things[]={
"Thing 0",
"Thing 1",
"Thing 2",
"Thing 3",
"Thing 4",
"Thing 5",
"Thing 6",
};

const int numberInHat = sizeof(things) / sizeof(things[0]);

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

void loop()
{ // randomHat test
  for (int i = 0; i < numberInHat; i++) {
    int x = randomHat();
    Serial.print(x); Serial.print(" ");
    Serial.println(things[x]);
    delay(50);
  }
  Serial.println("----");
}

int randomHat() {
  int thePick = -1;    //this is the return variable with the random number from the pool
  int theIndex;
  static int left = 0;
  static int randArray[numberInHat];

  if  (left == 0) {                                // hat is emply - all have been choosen - fill up array again
    for (int i = 0 ; i < numberInHat; i++) {    // Put {0, ..., n} into randArray.
        randArray[i] = i;
      }
    left = numberInHat;
  }

  // bEmpty always false at this point.
  while (thePick == -1) {
    theIndex = random(numberInHat);                  //choose a random index from number in hat
    thePick = randArray[theIndex];
   }

  left--;
  randArray[theIndex] =  -1;        // value theIndex is not longer available.
  return thePick;
}


The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The supply voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.


It looks like you want to use the "analogValue" to control the direction and speed of your DC motor.  If this is correct consider using this:

      //This method assumes: The center position of the pot is the motor's 0 speed point,
      //(because this is an ideal speed to actually reverse the motor's direction).
      //A PWM control range of 0-255, and the ADC input range of 0-1023.

      //First create a relative speed value from "analogValue",
      //with the pot mid point at 0 speed, and pot high/low points being full speed.

      int motorSpeed = 0;
      if (analogValue < 512 )
      {
       motorSpeed = map(analogValue, 0, 511, 255, 0);
      }  //Note that mapped range is reversed to give 0 speed at mid point.
      else
      {
       motorSpeed = map(analogValue, 512, 1023, 0, 255);
      }

      //then replace each analogWrite(E1, 255) with:
      analogWrite(E1, speedValue);

      //you should also change "  if (analogValue > 2 && analogValue < 500) {  " to:
      if (analogValue < 512) {


Using IMU for a small Arduino and bluetooth support

If you're new to Arduino I'd suggest avoiding the Mini and the BULLSH-fun that external programmers bring.
Something like the Pro Micro is much easier, almost as small, and less likely to bite.

Often the best way to pick hardware is to look for a tutorial (like This one) before deciding what to buy. While I personally haven't used IMUs it looks like the "6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345" from SparkFun would be (relatively) easy to use.

I've used the RN-41/2 Bluetooth modems (the same as are found in BlueSMiRF modules) and usually gotten on OK with them. There are plenty of tutorials available with a bit of Googleing.

Adafruit do a good line of Lipo batteries and chargers. They also have wireless charging modules if you're looking for extra brag-factor.

Hope this helps.


Can a Arduino Uno handle all these components?

I think you're fine depends on the gyroscope model and lcd.
-For ultrasonic sensor thats 2 pins
-the lcd needs at least 6pins but with an i2c adapter you only need 2 pins
-3 push buttons 3 pins
-one pin for the buzzer
Plenty of room left on the uno


How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?

Android devices usually don't have a USB host: they expect to be connected to some smarter device like your computer. Same goes with Arduino.
For this reason Arduino made the Mega ADK (that means Accessory Development Kit).

Mega ADK and Due act as USB hosts and can be connected directly to your Android phone. If you already have a board, another option is to get a USB host shield to add USB host capababilities.

Your sketch will tell the phone what kind of accessory application it is and your phone will download the appropriate application from the store.

There is a book about connecting Arduino to Android.


I am posting a code please try it may be it can help you
    #include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

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

#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
     rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
  }

  // When time needs to be re-set on a previously configured device, the
  // following line sets the RTC to the date & time this sketch was compiled
  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // This line sets the RTC with an explicit date & time, for example to set
  // January 21, 2014 at 3am you would call:
  // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.print("Temperature: ");
    Serial.print(rtc.getTemperature());
    Serial.println(" C");

    Serial.println();
    delay(3000);
}

Upload the above code and then upload the same code just comment the following part
if (rtc.lostPower()) {
        Serial.println("RTC lost power, let's set the time!");
        // When time needs to be set on a new device, or after a power loss, the
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
         rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
      }

This will work and even if you plug and unplug it from power the RTC time will not reset


Is the C++ STL fully supported on Arduino?

The STL is not a part of Arduino IDE.

Although efficient by desktop standards, the consensus is it doesn't fit comfortably in an Arduino's limited space.  That said, here's someone who seems to have done it:

https://github.com/maniacbug/StandardCplusplus

Check out the forks, they seem more up to date


Use the millis() function instead if you can accomodate a rollover after 50 days.

Take a reading of millis() at the start time.
time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.


Osepp DS1307 RTC program error (tmElements_t tm; does not name a type)

According to example ReadTest/ReadTest.ino, you have to include

#include <TimeLib.h>

See also comment from Alexander below (unchecked by me) that Time.h needs to be referenced.


Corrupted characters with an OLED displaying thermocouple output

The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page").  Because you are taking a reading for each chunk, the temperature can change.  Just pull the reading out of draw and do it once in loop:

double c; // a global variable used in draw and loop

void draw() {
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void loop() {

  c = thermocouple.readCelsius(); // set the global variable once

  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}


Efficient periodic wake up for sensor reads

Please refer to http://playground.arduino.cc/Learning/ArduinoSleepCode

it explains the details of a the sleep command and interrupts to re-a-wake. Where the power savings is from putting the resources individually into low power mode.

In your solution, you may want to put everything in low power, except power_timer1_disable(). Where timer1 would be configured to provide an overflow interrupt, say every 1 minute or longer and then go back to powering all off and return to sleep.

Note the article also mentions that the UNO's power supply is a linear regulator, which is very in-efficient. You may want to use your own. You can also get away with just running directly off of 2-3 AA's, if your other circuitry does not care. If this, then I would also suggest enabling the brown out detection, to ensure low battery does not get funny.


Explanation

The SoftwareSerial library requires continually polling the serial ports over short periods of time therefore it presents a problem of having to parse received data into something usable, which is going to be nearly impossible as your program is going to be too busy trying to keep up with all the incoming NMEA characters to assemble it all into something meaningful.

So in your situation the data from the ESP8266 module is probably fine as you say, but parsing it and sending it to the lcd over I2C is a lot of work and sometimes it will "lose" data it simply doesn't have time to process. This explains why the data loss is hit and miss, and gets resolved when you reduce the processing workload of your program by removing the lcd component.

Solution

What you need here is to use an interrupt-driven SoftwareSerial library instead, which works by filling a buffer in the background with received data and allows a little breathing room to process the serial data. A great example is the NewSoftwareSerial library. This link will show you how to use the library , also expand into the details my answer to give you a deeper understanding.


The 1k (pulldown-)resistor must be placed at the other side of the button (the pin8 side, not the 5v side).

The led needs a resistor, to limit the current.

There is no need for the buttonstate variable, as you can just check the brightness to see if the PWM value must be changed.

int ledpin = 9;
int pushbutton = 8;

int brightness = 0;
int fadeamount = 1;

void setup ()
{
  pinMode (ledpin,OUTPUT);
  pinMode (pushbutton,INPUT);
}

void loop ()
{
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in led
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out led
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);
  }

}


Urgent need of help splitting a JSON formatted string received by UDP

Two possible approaches:

Tokenize the string using strtok(), probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
An excellent opportunity to use an existing library, such as ArduinoJSON, which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from Decoding JSON)

#include <ArduinoJson.h>

// [...] other code

char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

//
// Step 1: Reserve memory space
//
StaticJsonBuffer<200> jsonBuffer;

//
// Step 2: Deserialize the JSON string
//
JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

//
// Step 3: Retrieve the values
//
uint16_t    u1 = root["U1"];
uint16_t    u2 = root["U2"];
uint16_t    u3 = root["U3"];
uint16_t    i1 = root["I1"];
uint16_t    i2 = root["I2"];
uint16_t    i3 = root["I3"];


What would be the architecturally-right place to put custom -D defines?

That is a tough one...  Because arduino-builder is basically a custom go script you don't get the facilities you get in a Makefile, like shell execution.

I would be inclined to do this kind of thing outside that environment - use some external program or tool to generate a config.h file (maybe use something like GNU Autotools) that contains your custom defines. That can then be #included in your sketch.


Can you use an Arduino UNO as an EEPROM programmer

You need 24 GPIO pins to control that EEPROM chip. The Arduino has 19, and a typical shift register has 8 outputs. It takes 3 or 4 (depending on the shift register) to drive the shift register.

That's 19 + 8 - 4 = 23 for a shift register that needs 4 pins, or 19 + 8 - 3 = 24 for one that needs 3 pins.

However I would assume that you want to communicate with your computer as well, and that means that pins 0 and 1 of the Arduino are out of bounds, since they are used for the PC communication.

That means, at best, you have 22 pins when you need 24.

So, no, with that combination you can't, due to a lack of pins.

However an IO expander, such as the MCP23017, would give you enough pins and need fewer pins to drive. They also work in both directions, so can be used for pins that want to be read as well as written (data pins).

Alternatively an SPI or I2C connected EEPROM would be the better option, since those are designed to be driven by a small microcontroller like an Arduino uses.


Several issues in the code you posted:

Every change to the text you do inside the for loop, will not be reflected to the LCD until the for loop will end (when i<limit will no longer be a true statement). You might want to add an additional code, inside the for loop and outside any of its conditional statements, that will repeatedly set the cursor and print input to the LCD. Something similar to the code you have prior to the for loop:

void intext()
{
  ... // rest of the code until the for loop

  for (int i; i<limit; )
  {
    ... // all the conditions for up/down/left/right/ok

    lcd.setCursor(0,1);
    lcd.print(input);
  }
}

Another problem is that when the user clicks left, the counter should be decremented, not incremented, and you should check for left boundary:

if(digitalRead(le)==HIGH && i>0) // left boundary check added
{
   delay(1000);
   i=i-1; // and not i=i+1;

}

After clicking Ok, and since the for loop does not increment i, the condition in the for loop (i<limit) will stay true, and the loop will not end until the user will click Right once more. To mitigate this, change the following

if(digitalRead(ok)==HIGH)
{
  lim=i; // and not: lim=i+1;
  delay(1000);
}

Otherwise, the user will have to click Right for completion, to increment i once more.

jfpoilpret comment about pull up/down is very important. Make sure you use pull up/pull down resistors in order to prevent input debounce (more details inside this link).


There is no cache, so you don't need to worry about that. All instructions are fetched direct from flash and executed straight away.
There is, though, a 2-stage pipeline. That means that in one clock cycle an instruction is fetched from flash, and in the next clock cycle it's executed - and while that is being executed the next instruction is being fetched ready.
That means that when a branch occurs, since the AVR uses a very very simplistic approach to branch prediction (i.e., it assumes the branch will not be taken and just loads the next instruction regardless), it has to discard the contents of the pipeline and start from scratch.
That's only a one clock penalty while it loads the newly-branched-to instruction, but it's still a penalty.
Cache is only needed when the CPU core runs faster than the memory can be accessed. Since the AVR only runs at up to 20MHz that is considerably slower than the flash can be accessed, so adding cache would be completely pointless. Other faster MCUs do use caching, such as the 200MHz PIC32MZ, since otherwise "wait states" would have to be introduced to slow the reading from flash down.


Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up).
If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed.
Motors usually have a RPM (speed) specification.
Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches.
You can also get Motor Controllers like...
https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter.
NOTE reducing DC voltage will result in less torque and higher current.
Hope this helps.


strcat gives error when I try to add a char to a char array

A char is a single character. A char * and a char[] are both arrays of characters (more correctly char * is a pointer to an array of characters).

strcat expects two arrays or pointers to arrays of characters. If you want to add a single character you can either fool the compiler into thinking that the character is an array of characters of size 1 (but it lacks the required NULL termination) or manually manipulate the target array.

For the former you could use strncat and casting:

strcat(some_char_array, &c, 1);

That gives you a pointer to the character, which is as far as the compiler is concerned, indistinguishable to a pointer to an array of characters. You use the "n" variant of strcat  to limit it  to just one character (plus an added NULL character) so it doesn't rely on the missing NULL termination.

For the second you could do:

int n = strlen(some_char_array);
some_char_array[n] = c;
some_char_array[n+1] = 0;

That just sets the Nth character in the target array to whatever is in c, then adds a new NULL termination character to the end.


Arduino FIFO queue for with potentiometer values and 7 segment display

Without seeing the code it is bit difficult to help. Please edit your answer and include the relevant parts of the code, otherwise we will end up (re)writing your code for you.
Hint: why not, when you detect a change in the pot, take the new reading, and then count down/up slowly (at the rate that you desire) from the currently displayed reading to the new measured reading - using a for loop, which contains a delay()? With each iteration of the loop you can display the new value. Easy!
However, this sounds like a terrible idea
Note that your code won't do anything else whilst the display is incrementing and decrementing, using this method. So, if you were to spend a lot of time twiddling with the knob, then the code wouldn't get much time to actually do any real work, apart from displaying the updated value.
In order for your code to do real work, whilst displaying the new updated value, you would either need interrupts, or integrate the display updating procedure into the loop(), such that each iteration of the loop() updates the display (or upon each n iterations of loop(), as loop() will probably be looping to quickly. You will probably need to use millis()).
NOTE: From a UX aspect, although it all sounds very 1960's-James-Bond-evil-guy-equipment, the whole notion of the displayed value slowly following the actual location of the knob sounds, at best, extremely infuriating, if not down right dangerous (depending upon the context). Human feedback should be as fast as possible. Else the user will constantly be turning the knob to reach the value that they which to achieve, when in fact they have already passed that value, and may be over compensating, and it is just the fancy display graphics that is showing the wrong value.
Assuming that the knob is controlling something else (actuator, motor, heater, etc.), and not just a pretty display in itself, unless, you are actually outputting the delayed displayed digital value, and not the knob's actual current analogue value, I would seriously recommend against doing this.
I may be wrong, and it would probably require a separate question on SE.UX, although, I would imagine that it has been asked already.


How do I make a counter that counts the amount of active inputs

You need something like:

const int BUTTON_MAX = 29;
const int button[BUTTON_MAX] = { 5, 6, 7, ... };
const int GREEN_LED = 2;
const int YELLOW_LED = 3;
const int RED_LED = 4;
int current_led;

void setup()
{
   // Setup inputs (buttons)
   for (int i = 0; i < BUTTON_MAX; i++) pinMode(button[i], INPUT_PULLUP);

   // Setup outputs (led)
   pinMode(GREEN_LED, OUTPUT);
   pinMode(YELLOW_LED, OUTPUT);
   pinMode(RED_LED, OUTPUT);

   // Initial state
   current_led = GREEN_LED;
   digitalWrite(GREEN_LED, HIGH);
   digitalWrite(YELLOW_LED, LOW);
   digitalWrite(RED_LED, LOW);
}

void loop()
{
   // Count number of active buttons
   int count = 0;
   for (int i = 0; i < BUTTON_MAX; i++) count += digitalRead(button[i]);

   // Map number of active buttons to led
   int new_led;
   if (count < 12)
      new_led = GREEN_LED;
   else if (count < 20)
      new_led = YELLOW_LED;
   else
      new_led = RED_LED;

   // Check for change and update
   if (new_led != current_led) {
      digitalWrite(current_led, LOW);
      digitalWrite(new_led, HIGH);
      current_led = new_led;
   }

   // Add a few milli-seconds for debounce
   delay(20);
}


I would use something like below. The optical isolator (PC817 or similar) protects your ESP.

Use a 1.0-1.5K resistor from the incoming SCART switch signal (SCART pin 8) to the anode of the Opto isolator (pin 1 in case of the PC817). This will limit the current through the PC817 internal LED to about 10mA with a 12V signal but the PC817 can survive up to 50mA, i.e. up to 60V on the SCART plug and even then will not damage your ESP processor.

Connect SCART ground (pin 14) to the cathode of the Opto isolator
(pin 2).

Connect a 3.3K - 4.7K resistor to the collector of the phototransistor of the PC817 (pin 4 of the PC817) and connect the other side of this resistor to Vcc of your ESP (+3.3V) as a pullup.

Connect pin 3 (emitter) of the PC817 to the Ground of your ESP.

Connect a digital input pin of your ESP to pin 4 (phototransistor collector) of your PC817 to create an active-low signal indicating your set top box is active.

This is the schematic you could use:

simulate this circuit – Schematic created using CircuitLab


PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.

If you grep that folder (location dependent on tool and installation options) you will find a file called iom328p.h that defines

#define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.


From the arduino.cc website.

"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"

It sounds like you need the 12V PoE module


SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)

AVR274 describes a single-wire, half-duplex software UART.

AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.

AVR307 describes implementing a half-duplex UART using a USI.

All code associated with each app note can be downloaded from Atmel's website.


the heat is from the supply lines of board.

it's not the chip itself, as if it gets hot like that the chip should be destroyed.
it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too.
so the heat is not from the chip. its from power supply tracks on the PCB.

use another power source for the LED strip.


MQTT is TCP/IP native. If you want to access it via Bluetooth, you need a gateway; a device that translate protocols. You need one for the specific protocols involved: MQTT, TCP/IP and Bluetooth.

Google "MQTT Bluetooth gateway" to find alternatives like this one:

  The iGS01 gateway listens for beacons, gets their advertising data and
  forwards it on to your server or an IoT server via TCP, HTTP(S) or
  MQTT. It can be used to feed back-end systems that report on the
  presence or absence of iBeacon or Eddystone beacons or act on beacon
  sensor (e.g. accelerometer, temperature, light, humidity) data.

  The gateway connects to your local 2.4GHz frequency band WiFi access
  point and is managed via a web browser interface. It can  be connected
  via WPS (press button on both the gateway and the WiFi access point).
  It can also be managed via Telnet commands from other hardware (or a
  human).

  For MQTT/MQTTS, the host, port, username, password and a root CA cert
  can be provided.

There are also software only solutions available, but I didn't found a generic one, only specific for certain vendors.


Comparing custom variable type definitions

In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

Serial.write("ODB State: ");
switch (odb.getState()) {
  case ODB_DISCONNECTED:
    Serial.write("Disconnected");
    break;

  case OBD_CONNECTING:
    Serial.write("Connecting");
    break;

  case OBD_CONNECTED:
    Serial.write("Connected");
    break;

  case OBD_FAILED:
    Serial.write("Failed");
    break;

  default:
    // Error case
    break;
}
Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.


How to identify Adafruit Feather 32u4 via mac id/UUID/etc

I'm quite sure the reason they print a mac address on a sticker and put it in the package is that they have no way of storing the address in the the feather wing, or at least don't bother to do so if there is a place to store it.

It's up to you to get that address to your Ethernet.begin() call.

FYI, I have been trying to use EEPROM to store the mac address, but the bootloader appears to blow away EEPROM with every reboot.  If I figure that one out I'll update.


The Arduino main() calls loop() continuously, in a tight loop. Thus
your AllTimer::setTimer() is called continuously, and each time it
resets the counter (TCNT1 = 0x0000;). Thus the counter can never
overflow.


They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly.

In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.


It turns out the problem was the A2 pin on the board.

When I used the A0 pin (or a different board) the problem goes away.

I realised something was wrong when I noticed the values from the pot were strange (I expected values in the range 0 - 1023, but was receiving values from 170-250 ish).


Most precise way to measure Linear distance travelled by a wheel

If you measure  one of the free running wheels (with no motor connect to it), it depends on the traction of the wheel, but that could be fairly accurate.
If you move horizontally a simple accellerometer (1 axis) would be great. But if you have a vertical component, then you can not distinct between accelleration and weight force (Einstein). If you use a 3 axes accellerometer, you can compute/extract the robots moving speed (subtract the G component = 9.81 m/s²) and thus the distance. You have to use vector arithmetic in this case.
If the ground has enough "structure" you could use an optical sensor (like optical mice have).
If you have a reference object (e.g. a wall, a book) you could use a LIDAR sensor (https://en.wikipedia.org/wiki/Lidar) to measure the absolute distances at time points and compute the relative distance between these time points.


What's the most accurate way to time-stamp analogRead data?

There is no more accurate way of getting time on the arduino, but I would suggest you use millis() instead.

micros() returns microseconds, or millionths of a second, since the arduino was turned on. The issue is that the 32 bit unsigned integer used to store time on the arduino can only count about 70 minutes worth of micros before overflowing and resetting to 0. (see http://arduino.cc/en/reference/micros)

millis() is in thousandths of a second since the arduino turned on, and it will not reset for about 50 days. If you think one thousandths of a second is good enough resolution, it will probably be the better choice.

If you need time to be absolute, as in the current day/hour/minute, you will need to buy a real time clock to plug into the arduino. They are about 20 bucks, and available from all the standard arduino accessory stores like sparkfun, adafruit, ect.

On your question of the order, both commands run so quickly, I can think of no reason it would matter.


How to empty the buffer for Serial port?

It's quite simple to empty the serial buffer - you just read all the data that is in the buffer and throw it away:

while (port->available()) {
    port->read();
}


I use CoolTerm, which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).


One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.

The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.

Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.


Adafruit Feather 32u4 BLE compatible with Software SPI?

Read SparkFun's guide, Serial Peripheral Interface (SPI), especially the multiple slaves section:

Multiple slaves
There are two ways of connecting multiple slaves to an SPI bus:

In general, each slave will need a separate SS line. To talk to a particular slave, you'll make that slave's SS line low and keep the
rest of them high (you don't want two slaves activated at the same
time, or they may both try to talk on the same MISO line resulting in
garbled data). Lots of slaves will require lots of SS lines; if you're
running low on outputs, there are binary decoder chips that can
multiply your SS outputs.

On the other hand, some parts prefer to be daisy-chained together, with the MISO (output) of one going to the MOSI (input) of the next.
In this case, a single SS line goes to all the slaves. Once all the
data is sent, the SS line is raised, which causes all the chips to be
activated simultaneously. This is often used for daisy-chained shift
registers and addressable LED drivers.

Note that, for this layout, data overflows from one slave to the next,
so to send data to any one slave, you'll need to transmit enough data
to reach all of them. Also, keep in mind that the first piece of data
you transmit will end up in the last slave.
This type of layout is typically used in output-only situations, such
as driving LEDs where you don't need to receive any data back. In
these cases you can leave the master's MISO line disconnected.
However, if data does need to be returned to the master, you can do
this by closing the daisy-chain loop (blue wire in the above diagram).
Note that if you do this, the return data from slave 1 will need to
pass through all the slaves before getting back to the master, so be
sure to send enough receive commands to get the data you need.


How to access Attiny84 port B in Arduino IDE code?

According to the ATtiny web-page the pin/ports are numbered as below:

The physical pin 2 is the Arduino ATtiny core pin 10. You can also find this well documented in the pins_arduino.h file.

Cheers!


Can regular Arduino pins be used during SPI?

I did not check the datasheet of the RF69, but it is customary for SPI devices to have a “slave select” input pin. When such a device is not selected, it will leave its MISO pin in high impedance and completely ignore whatever may happen on the MOSI and SCK pins. This effectively disconnects the device from the SPI bus. In this situation you show be able to play with the LED without disturbing the device.

Beware that the slave select pin is usually active low: write it to HIGH to deselect the device.


How much power can a proto board handle?

No, it's not practical do to that with protoboard of any form.

There are two reasons for this:

Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.


Conflicts with USB and external power supply

Why do you suspect a potential difference? Where is th 7V coming from? If the 7V power supply is free floating and used for nothing else, there is no source for potential difference.

A typical wall wart will have a free floating output.


I searched quite some time for everything regarding the MPU6050, but there is just rumors and jokes about the dmp funcionality. One project encorporates the hard reverse-engeneering some wise people did, which is: http://www.i2cdevlib.com/docs/html/class_m_p_u6050.html

This also uses the interrupt, which I suppose you can't really avoid. Why exaclty this would be necessary though, is not a thing I could tell you.. I assume, that the dmp works somehow with the fifo buffer and can only interact through it. The cited library has examples with and without dmp, which I can really recommend.

Using this thing for a quadcopter however I can just say, that the dmp is too slow to control such a fast system, so maybe first consider what you really need. From my experience it does some magic things, but acts strange is due to it's not documentary it is a pain to work with.

Hope this helps.


Arduino Mega not recognized by device manager

hey i had the same problem, i am thinking because i installed atmel studio and then this started happening,
I then downloaded arduino from the microsoft store,(no change)
then i restarted the pc, now its compiling and uploaded normally but still does not show the name of the board that is connected just shows lets say just  COM22 with out saying what board


Step 1: Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.

Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.

Step 3: Open Arduino IDE and Paste the source code in the window just like shown in the picture.

Step 4: You are ready to send At Commands to Your ESP8266 Module. Remember you will see a Garbage value during Serial Communication.

AT – Will give OK on the serial monitor, if Not just unplug vcc Pin of ESP8266 Module for a moment and reconnect again.

Send AT+RST – Command to Restart module / Optional Command

Send AT+GMR – To get the firmware version

Send AT+CWMODE? – Set Module to a Dual Mode Sucha as Standalone + Access Point mode.

Send AT+CWLAP – Command to Search Nearby Wifi Access Point. Find your Wifi Name in the Search Result.

Send AT+CWJAP="Your Wifi Name","Your Wifi Password" – Command to Connect to WIFI.

Send AT+CIFSR – Command to Check Allocated Ip given by your Wifi to your ESP8266 Module/Optional Command.


Problem receiving data from RPi to Arduino via serial

The problem may be with your code, especially the function for opening the port. Try this in Python 3 and see if it works.

import serial, time

ser = serial.Serial('/dev/tty/ACM0', 9600, timeout=1)

while ser.isOpen():
    try:
        ser.write(b'Hello')
        time.sleep(0.1)
        print('Received: ')
        while ser.inWaiting():
            print(str(ser.read(), encoding='ascii'), end='')
        print()
    except KeyboardInterrupt:
        ser.close()

Arduino side:

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

void loop(){
  while (Serial.available())
    Serial.write(Serial.read())
}

Crude, but it is a lot more straightforward than your program and will help you isolate the problem.


Computer not detecting my Arduino MEGA 2560 R3

If your Mega has an ICSP header for the USB chip (circled below) then you can test that chip.

You can use another Arduino (eg. a Uno) to detect the signature on that chip, as per my sketch on Sketch to detect Atmega chip types.

All you need is 6 hookup wires to connect your testing board (the known good one with the sketch on it) to the ICSP header on the Mega. Note the pin orientation. I have circled the correct header pins, and pointed to pin 1. On the board pin 1, has a small white dot.

Below are the ICSP pin names, seen from above (component side).

Wire the Uno to the chip being tested as follows:

Arduino Uno      Target chip

D10 (SS)            /RESET
D11 (MOSI)          MOSI
D12 (MISO)          MISO
D13 (SCK)           SCK

Gnd                 GND
+5V                 VCC

Check your wiring! If you wire things around the wrong way you can turn a good chip into a bad one.

Important! Only attempt this process if you can see that you have an ATmega8U2 or ATmega16U2 chip on your board (see below). If you have something totally different this will not work. In that case you probably have a cheap clone board.

Using the Serial Monitor on your Uno, you should then see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x93 0x89
Processor = ATmega8U2
Flash memory size = 8192 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xFF
Clock calibration = 0xAB
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 1000

Bootloader:

1000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
1010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
1020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xCB 0xC4 0x00 0x00
1030: 0x4E 0xC0 0x00 0x00 0x4C 0xC0 0x00 0x00 0x4A 0xC0 0x00 0x00 0x48 0xC0 0x00 0x00
...

My board had a ATmega8U2 on it, yours might have a ATmega16U2. However the concept is the same. If you see something like that, the chip is (probably) good. At least it responds to programming commands.

If you see something like

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  7 2015 at 10:47:47 with Arduino IDE 106.
Attempting to enter ICSP programming mode ......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

Then either you made a wiring error, or the chip is bad.


light detection system: Response different from power bank and computer system

Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons.  More may exist.

The USB 2.0 definition stats such a port provide 0.5A of current.  Some devices limit the current as a precaution.  Therefor the battery may provide more current then the USB source.  The type of USB source was not specified and no voltage measurement data was provided.
How fast does the device need to react to a change in light level?  A light-dependent resistor or LDR can have a latency of as much as a second with respect to light level changes.
With regards to the 16 bit ADC.  What precautions have been made with regards to precisely controlling the ADC's voltage reference?  Any fluctuation can cause large errors.  What precautions have been made with regards to filtering out the ADC's random noise?  For example, many ADCs only have a fraction of their resolution if averaging is not used.


Yes, it is possible - after all, the Arduino is essentially just a bunch of incredibly tiny transistors. Early computers, before ICs were invented, were built from transistors. Before that it was valves. Before that it was relays. All just, at the end of the day, switches.

Would it be a practical project? Not really, although someone has done it (not for the AVR CPU, but the concept is the same): http://www.megaprocessor.com/

How would you start? Well, first off you'd create the basic building blocks of a CPU, which is logic gates. There are two basic ones that can be combined together to make any other gate: the NAND gate and the NOR gate. You'd pick one of those and put lots of them together to make the basic sections of the CPU. Then those blocks connect together to form the CPU. More logic gates go together to make the IO functionality, memory, interfaces, etc.

Basically:

Transistors combine to make NAND gates (or NOR gates if you prefer that form)
NAND (or NOR) gates combine to make complex gates.
Complex gates combine to make logic functions
Logic functions combine to make logic blocks (like the ALU)
Logic blocks combine to make the CPU


Just a few points:

You can't measure DC current with a coil; you would need a Hall-effect sensor;
The charging current and the voltage you measure will depend on the state-of-charge of the battery, making it difficult to compare measurements;
You can't fully charge a nominally 12V battery with a 12V solar panel; a 12V lead-acid battery with the panel you mention in the comments should work;
You need at least a diode between solar panels and battery, and possibly a proper charger, depending on the chemistry and capacity of the battery and the maximum charging current; maximum charging current for a 12V 9Ah lead-acid battery is about 1A if you stay on the very safe side, so the panel you mention should be OK; just don't overcharge the battery;
You need to be sure the battery voltage doesn't exceed 12V by too much, or the voltage divider will put more than 5V on the Arduino's input pin and fry it. Nominally 12V lead-acid batteries are usually charged to about 14V, and the solar panel you mention can get there. This would put 5.6V on the Arduino input pin with the resistor values you use in your voltage divider.

Also have a look here: Measure power of solar cell with an esp8266.


ESP8266-01 connected to Arduino Mega - Current output?

Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.

So you will need an external power source that can provide enough current.

  I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.

You are right to want to ditch the voltage regulator though.

As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.

9V -> [REG] -> 5V -> [REG] -> 3.3V

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.

Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.

Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.

There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard (I myself sell one on eBay that I designed).


Can i burn an Arduino sketch .hex directly using USBASP?

Sure you can - but you don't even need to remove the chip from the Uno.

The 6 pin header at the end of the board (used for SPI) is also the ISP header for the main chip. Just plug your USBASP into there (you can get adaptors for it for $0.99 off eBay) and program it direct.

I think there's even an option in the IDE's menu to select the USBASP as the programmer (or there used to be on earlier versions).


ADXL345 Data Rate seems to depend more upon Baud rate than the actual Data Rate that I set

You do know that sending data through serial takes time, don't you?

You are sending 41 bytes per reading. The serial port has a 64 byte buffer. By the second reading the buffer is full and all printing blocks until there is room in the buffer.

At 38400 baud that's sending 3840 bytes per second. With 41 bytes per reading that's 93.66 readings per second (not including the time taken to do the actual reading) that you can squeeze down the serial port.

Either run at a faster speed, or reduce the quantity of data you're sending per reading - or do both.


Error while updating ThingSpeak using SIM808

It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE" (from https:// to http://)


Your problem lies in these lines:

esp8266.println("AT+CIPSEND=0,75");
esp8266.println("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.println("Host:www.homeautomationserver.com\r\n\r\n");

You are mistakenly using println() instead of print() when sending the data. That imposes its own <CR><LF> sequence on the end of the lines, yet you are adding the <CR><LF> manually.  You are also incorrectly specifying 75 characters to send, so the result of all that is:

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
\r\n                                                  2
Host:www.homeautomationserver.com\r\n                35
\r                                                    1
                                                   ----
                                                     75

I.e., your request is garbled. You need to change the println() to print() for the data printing and make sure the character count is correct:

esp8266.println("AT+CIPSEND=0,74");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Host:www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Host:www.homeautomationserver.com\r\n                35
\r\n                                                  2
                                                   ----
                                                     74

You should also include more detail and commands in your headers. Things like the length of the body (0 bytes) and the fact that the connection should be closed, and there really should be a space after the colon on the Host: header:

esp8266.println("AT+CIPSEND=0,113");
esp8266.print("GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n");
esp8266.print("Connection: close\r\n");
esp8266.print("Content-Length: 0\r\n");
esp8266.print("Host: www.homeautomationserver.com\r\n\r\n");

GET /f/pw9e1acqx7yb0gl.txt HTTP/1.1\r\n              37
Connection: close\r\n                                19
Content-Length: 0\r\n                                19
Host: www.homeautomationserver.com\r\n               36
\r\n                                                  2
                                                  -----
                                                    113


Use chars in quotes in const char* as name of function

Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.
An example:
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}


Help, I want to turn relay constantly on until a difference is detected, but triggered only one instead

As far as I can see, the relay will stay on when val is less or equal than 500, and stay off when val is higher than 500.

However, there might be a problem when val keeps fastly moving around 500; it will switch on and off quite fast.

To prevent this, you should make two 'triggers', e.g. turn it on when the value <= 480, and turn it off when the value >= 520. When it is in between 480 and 520 it will not change. This will cause less fast changes of the relay. Of course if the initial value is already between 480 and 520 you have to make a choice yourself.


US-100 Ultrasound sensor doesn't work on Arduino mega 2560

Have you removed the "Serial Data Mode" shunt to put the device in "Pulse Width Mode"?

On the other hand, perhaps the "Serial Data Mode" would actually work better for your application?

Where I work, we have a coding style that strongly encourages
all "magic numbers" to be documented
with a link to the website it came from
or a reference to the book and page it came from.

Would something like this work for you?:

void loop(){
    // Trigger US-100 to start measurement
    // at least 50 us high, then set it low,
    // as recommended by
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    digitalWrite(trigger,HIGH);
    delayMicroseconds(50);
    digitalWrite(trigger,LOW);
    // Acquire
    unsigned long echo_microseconds = pulseIn(echo,HIGH);
    // debugging
    serial.println( echo_microseconds );
    Serial.println(F(" microseconds"));
    // conversion factor from
    // https://www.bananarobotics.com/shop/US-100-Ultrasonic-Distance-Sensor-Module
    unsigned long distance_mm = echo_microseconds * 34 / 100 / 2;
    Serial.print(distance_mm);
    Serial.println(F(" mm"));
    delay(50);
}

It might be easier to use the Ping library as described at
Arduino-Info: UltraSonic Distance Measurement.

You might find the
Arduino Forum: Measuring Distances with Ultrasonic Sensors
thread educational.


Nano can't get reply from ENC28J60 Ethernet Shield

The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.


Bluetooth Master and Slave to track device's locations

Bluetooth generally support only one to one connection. Atmost 6 bluetooth can be connected to single module in latest bluetooth version(the basic model probably used by you connects only 1 device). Hence it is not a good idea to use bluetooth. Also if you need a web based platform you should switch to some more powerful platform like raspberry pi, beagle bone etc.


Problem with simple coding for PLDuino: trying to turn relay on and off

For the library warning, you'll need to add / edit library.properties to those folders to specify a valid category.

This is an example library.properties to give you a feel for the structure (I found this particular one here).

name=TMRpcm_PLDuino
version=1.0
author=TMRh20
maintainer=digitalloggers
sentence=PCM/WAV Audio playback (USE_TIMER2 enabled)
paragraph=Play WAV audio files from SD card using AVR (UNO,Nano,etc) based devices.
category=Communication
url=https://github.com/digitalloggers/TMRpcm_PLDuino
architectures=avr

However, these are just warnings, and don't seem to be the cause of your problem.

Your actual problem in this case seems to be that it's trying to upload the sketch via COM4 and it can't find the PLDuino on that port.


2 sensors, add delay between each reading

I've read that it could be advantageous to set a small delay between
  temperature readings

Although temperature is typically a measure that changes slowly in time, there is nothing in programming/device side preventing you from making readings in short intervals; unless this added time is necessary to prevent issues on other tasks, but so it should be not related to that.


Debug-logging without using Serial.print and without WiFi

Yes, what version of Arduino are you using?

For Arduino Mega, you can use Serial.println for writing debug data and Serial1.println for communication with HC-05. (See Example: MultiSerial Example)
For other Arduino boards, you can use Serial.println for writing debug data and SoftwareSerial library for communication with HC-05. (See Example: SofwareSerial)


counting pulses from encoder on interrupt 0 pin every 50 ms

Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.

Remove the Timer and Wire Libs

add this code in void setup()

attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.

and attach your sensor/incoming pulse wire on Pin 2 on arduino.

make a new function like this

void_counter(){
pulses++;
}


Arduino thermometer and humidity display with 7 segment LED display

You need to maintain a state which tells your program whether you are displaying the temperature or the humidity.  Every time the timer expires you need to change from one state to the other, and then display the relevant value depending on what the state is.

Something like:

bool displaying = false; // false = temperature, true = humidity

void loop() {
    if ((millis()-timer) >= INTERVAL) {
        timer = millis();
        display = !display; // Switch between display values

        if (display) {
            float h = dht.readHumidity();
            sevseg.NewNum(h * 100, 2);
        } else {
            float t = dht.readTemperature();
            sevseg.NewNum(t * 100, 2);
        }
    }
    sevseg.PrintOutput();
}


Problems with compiling more then one sketch in the Arduino IDE

That sketch is written for the ESP8266, not the ESP32. The two are very different chips, and the libraries used are very different.
You will have to learn how the sketch works, and how the ESP32 libraries work, and port the sketch to the ESP32 once you have learned how.


How to count number of bytes appearing in the Arduino serial?

Serial.available() returns the number of bytes available for reading in the buffer.
int nBytes=Serial.available();
if (nBytes > x) {
............
............
............
}


It seems your serial does not have the right permissions to be opened in user mode. Try adjusting that by typing

sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).


How can I do this sentence show me in arduino

Your question is unclear.

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


I get the following error while using esp32

Welcome to StackExchange!

I guess you flashed esp32-cam firmware to off-branded ESP32-CAM with different pinout assignments.

To fix this, maybe you should try around with different settings.

Your code should have something similar to this:

// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
//#define CAMERA_MODEL_AI_THINKER

Now try to comment out the third line, and uncomment the last one. Probably it would help.


The problem is that LEN is evaluated locally for each usage replacing it with the content. In myFunction the parameter being passed to it is a pointer, not the array.
You need to evaluate the size once and once only in the context where the array hasn't collapsed into a pointer. That is usually done immediately where the array is defined:
const char* mainMenu[] = {"FirstWord", "SecondWord", " "};
#define MAINMENU_LEN (sizeof(mainMenu) / sizeof(mainMenu[0]))

Because mainMenu is a global it's always available, and when you require the length you get the length of the global array.
If you want to keep things local you will have to pass the number of elements in the array as a parameter to the function that uses that information.
myFunction(mainMenu, MAINMENU_LEN);

Another common alternative is to have some "end of array" marker and you loop through your array until you find that marker (that's how strings work - with \0 for the end of array marker):
const char* mainMenu[] = {"FirstWord", "SecondWord", " ", 0};

Then:
for (int i = 0; m[i] != 0; i++) {
    ...
}


That was a very raw way of trying to read a BMP file. There are a lot of assumptions that might give errors.

The file is a BMP file. The header signature is not checked.
The image offset is assumed to be directly after the file header. It is not read.
The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272>256 the low byte is 16.
The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.

A more robust method to read the BMP header and image information is to define them as a struct and read.

struct bmp_file_header_t {
  uint16_t signature;
  uint32_t file_size;
  uint16_t reserved[2];
  uint32_t image_offset;
};

struct bmp_image_header_t {
  uint32_t header_size;
  uint32_t image_width;
  uint32_t image_height;
  uint16_t color_planes;
  uint16_t bits_per_pixel;
  uint32_t compression_method;
  uint32_t image_size;
  uint32_t horizontal_resolution;
  uint32_t vertical_resolution;
  uint32_t colors_in_palette;
  uint32_t important_colors;
};

bmpImage = SD.open("Circle.bmp", FILE_READ);
...
// Read the file header
bmp_file_header_t fileHeader;
bmpImage.read(&fileHeader, sizeof(fileHeader));
...
// Check signature
...
// Read the image header
bmp_image_header_t imageHeader;
bmpImage.read(&imageHeader, sizeof(imageHeader));
...
// Check image size and format
...
// Locate the pixels
bmpImage.seek(fileHeader.image_offset);

The file and image information are stored in little-endian so that works just fine on an AVR.


Common wireless gadget with rotary encoder to connect with Arduino

That sounds like a candidate for building your own.  It shouldn't be too hard.

There's plenty of low-cost Arduino-compatible wireless modules available.  My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.

Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice.  Write the sketch.

Add another nRF24L01 to your main Arduino to receive whatever you send.

Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel.  I'm sure you could think of other things you could do with that wireless channel :)


Makeblock Arduino keeps stopping from motor overpower protection

It is unlikely the pause in operation is because of the motors.  It is more likely the Makeblock is stopping because the  motor controllers are too hot.  Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch.  If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.

An alternative explanation involves a limited power supply.  It could be that when the motors are demanding high current, the voltage drops and the processor resets.  Consider a power supply that can offer more amperage.  Or larger capacity batteries.


Look at the back of the module. There are 3 groups of 3 solder pads each, marked with A0, A1 and A2. With these pads you can set the 3 least significant bits of the address.

On the images in your product link these pads are unconnected. The middle pin is the address pin. The left pad (which is connected to a trace) is Vcc, the right pad (which is connected to the big trace area) is ground. By connecting the middle pad with ground, you set the address bit to zero. By connecting it to Vcc, you set it to 1.

As the pads are unconnected, the address pins are floating. In that state, the pin is reacting to random electrical noise, thus changing state randomly. So also the address changes randomly.

You need to connect every address pin to either ground or Vcc by adding a solder bridge to the pads.


L298N beeps and malfunctions when receiving certain analogWrite values

Ok, here is my theory what's happening:

Every motor has an amount of friction at his rotor. You need to pass enough energy to overcome this friction, or the motor will not move. When you use analogWrite(enr, 71) or lower, you pass only a small amount of energy to the motor, so that it cannot overcome the friction.

Now you have to understand, what analogWrite() really does. It does not output an analog voltage. Instead it generates a PWM signal. The voltage changes between HIGH and LOW level (5V and 0V in case of the Uno) at a specific frequency. The relation between HIGH time and LOW time is called duty cycle. That is, what's controlling the motor speed. So instead of supplying different voltages, we turn the motor on and off very fast. Since the rotor has a relatively big inertia (because of it's mass), it cannot react fast enough to follow these pulses. We only give it small pushes very fast. Instead it integrates over all the pulses. If the duty cycle is low (more LOW than HIGH time) only a small amount of energy is passed to the motor.

So, what is the motor doing, when it's got not enough energy to overcome the friction? It will still get little pushes very fast, but cannot actually spin. Instead the passed energy will induce vibrations in the motor, which have the frequency of the PWM signal. These vibrations can then be heard as a continuous beep.

If enough energy is passed to overcome the friction, the rotor spins correctly and does not vibrate, thus you cannot hear a beep.

What to do now:

The described principle applies to every motor, so cannot do much about that. You can simply go the easy way and not drive the motor with such low duty cycles. Another cause might be, that your motor likes to get a higher current to give it's full power. The L298N is quite inefficient, so you could change that to a H-bridge driver, that uses MOSFETs instead of bipolar transistors. Also maybe you can increase the voltage, that you use to drive the motor (depending on the not specified motor).

You didn't describe, how you have connected everything, so 2 other points: You cannot drive a motor from a digital pins power (since a digital output pin can only provide 40mA at max, 20mA recommended) and you should also not power a motor through the Arduino, since you might fry the voltage regulator or the protection diode. You can get away with that, when using small motors without any load, but that doesn't scale well. You should always connect the motor circuit directly with the power supply, so that the motors current does not have to flow through the Arduino.


The equation to calculate it is given in the first article you linked:

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your LENGTH define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve arbitrary frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.

So, to solve for OCR2A:

OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);


It isn't clear from the description whether your setup has a hardware problem or a software problem.  For example, the rationale for “I had to snip the RST leg from the shield” is unclear.

The comment in ladyAda's example, “Can alternately just connect to Arduino's reset pin”, means that it's suitable to hardware-reset the LCD at the same time the Arduino does a hardware reset.  If the “RST leg from the shield” that you snipped is the LCD reset pin, as opposed to a pin driven by the small tactile reset switch on the 2.8" mcufriend shield, you probably should restore that pin.  In other words, unsolder and remove the stub of the pin you snipped off, insert a new pin, and solder it in place.

Note, just reinstalling the pin might make things work.  It's possible the LCD is sitting there in a permanently-reset  state, due to its RST input hanging open.  It's also possible the library is already driving RST properly but that drive isn't getting through, due to the missing pin.  Whatever the case may be, with the pin in place you should be able to software-reset the LCD by pulsing A4.  (Ie, with consecutive digitalWrite() commands, in setup() and before shield initialization, take A4 high and then low, or vice versa.)

Edit: If A4 isn't available for resetting the LCD (due to its use as the SDA signal for I2C, per comment) you might try adding a jumper wire from the shield's LCD_RS pin (above A4) to an available pin, and adjust the #define LCD_RESET statement accordingly.

In general, to add a jumper wire, strip about 5 mm of each end of a short piece of #30 wire-wrap wire.  Form a small hook at each end.  Hold a hook onto the solder of the pin you wish to attach to and briefly heat the solder, letting the hook sink into the solder.  If you don't have wire-wrap wire, use a single strand from some old stranded cable (eg, mouse or keyboard).  Use thin heatshrink tubing or a bit of stripped-off cable insulation to insulate the jumper.  To keep pins in place while soldering, seat the pins being worked on into an old disk-drive connector, or another shield, or if you have nothing else, an Uno.

In your particular case, an mcufriend shield on an Uno, no pins are available unless you co-opt one of the SD-card-slot signals.  But before doing that, it's probably worthwhile to try your original idea of wiring to the Uno's RESET pin.  Your jumper would run from J3's second pin (A4) to J4's last pin (Reset), installed on the LCD side of the shield.  You should be able to see the trace between the Reset pin and the Reset switch, when identifying the Reset pin.