ATmega 32A and 2560 R3 register to pin mapping?

What is ATmega2560 R3? There is ATmega2560 MCU or Arduino Mega R3. do you want the mapping of pins of Arduino Mega or the pins of the ATmega2560 MCU.

The mapping of pins of the ATmega 2560 chip is in the datasheet.

The mapping of the Arduino Mega pins to ATmega2560 pins and registers is in the schema of the board or in the Arduino AVR boards package variants mega folder.

The link "Arduino's 2560 pin mapping" in your question shows the mapping too. Registers are PA, PB,... and every register covers to 8 pins with the 8 bits of the register. For example PB3 is pin 50 of the board.


Can a WiFi enabled Arduino make a HTTPS request to my Web Server?

It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.

How to get HTTPS on Arduino?

However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet).

https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/


You need:

two MCUs that can act as USB devices (one per slave),
some way of getting the commands from the master to the MCUs

That means two Arduino Dues (or Arduino Leonardos, or SparkFun ATmega32U4 breakout boards, etc.) and one USB device of some sort that you can talk to and have send commands to the MCUs.

And perhaps something to transport the commands from the master to the slaves, but you need to think about the programming for that first since the transport and the programming will be very closely connected.


printing the analogRead() functions result crashes Arduino

The capacitor you have is rather large on the Analogue input, normally at this position it would be for debounce. Try something in the range of 100nF. Another idea would be to increase R8 to 10k.
https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/


Multiplex 7 segment during delay (external IC?)

Perhaps a MAX7219 would do what you want.

  The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays.
  The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs.
  Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit.
  Only one external resistor is required to set the segment current for all LEDs.
  A convenient 4-wire serial interface connects to all common ¦ÌPs.
  Individual digits may be addressed and updated without rewriting the entire display.
  The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.


How to use a Pololu 5v AVR ISP Programmer to program an AVR at 3.3v

Since AVR ISP is simply a modified form of SPI, the most universal way to handle this is to use a 3/1 level translator such as the MAX3392E. Once you provide it with 5V on VCC and 3V3 on VL it will translate the MOSI, SCK, and nRESET signals to 3V3 and the MISO signal to 5V.


At low speeds and short distances that won't be a problem.

At high speeds (megabits per second) and long distances (hundreds of meters) you may get reflections unless you get the termination just right.


Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0)

I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.

My PHP Script

<?php
$humidity=$_GET['humidity'];
$data = array("protocol"=>"v2", //Compose JSON stream
              "at"=> "now",
              "device"=>"DEVICE_NAME",
              "data" => array ("humidity" => trim($humidity)),
              "checksum" => "");
$data_string = json_encode($data);

$ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'carriots.apikey: YOUR_API_KEY',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); //Send the stream

Note:

I switched to Carriots from ThingSpeak due to personal preference.
This is by no means a standard way to send stream to Carriots.This
involves additional effort which slows down transmission of data but
I decided that this setup will be enough for a hobby project.
A good understanding of how POST requests are built should allow me
to skip the extra PHP script completely.


Encode & decode boolean values into a single integer?

You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the bit number in there. The << is left shift.

#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

Now you can combine:

uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

if (val & PIN3) {
    // ....
}

To loop through the pins you can use the << again:

for (uint8_t pin = 0; pin < 8; pin++) {
    if (val & (1 << pin)) {
        // ....
    }
}

etc.


Yes, it just blindly chops off the upper 16 bits.  That means that the sign can change between the two.

For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.

To see that in more detail, look at the binary.  123456789 in binary is:

0000 0111 0101 1011 1100 1101 0001 0101

Truncate that at 16 bits and you get:

1100 1101 0001 0101

And of course the high (sign) bit is set, so the value is negative.


I2C 2 way communication between Arduino Uno and Arduino Mega

To join the bus as a master you cannot supply a 7-Bit slave address so your code has two slaves.

Below you will find 2 sketches that successfully sends data to a slave. I would suggest you start looking at the I2C protocol and understand there are 4 Modes:

Master->Transmitter
Master->Receiver
Slave->Transmitter
Slave->Receiver

All communications regardless of how the data is transferred requires a master. It's the master that controls the clock pulses, thats why its always the master that initiates the communcation.

The MasterReader/MasterWriter tutorials on the arduino forum should now possibly start to make a little more sense when understanding those modes.

This code shows how a master sends data to a slave, and then how it requests data from the slave. If we look at this code from the master point-of-view, you can see it essentially says, send this byte to the client (m->t & s->r), then request data from the slave (m->r,s->t)

Master Code

#include <Wire.h>

#define SLAVE_ADDRESS 0x60

void setup()
{
  Wire.begin();
  randomSeed(analogRead(3));
  Serial.begin(9600);
}

byte x = 0;

void loop()
{
  x = random(0,255);
  Serial.print("Sent: ");
  Serial.print(x, HEX);
  Serial.print("\n");
  Wire.beginTransmission(0x60);
  Wire.write(x);
  Wire.endTransmission();
  delay(500);
  Serial.println("Requesting Data");
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  int bytes = Wire.available();
  Serial.print("Slave sent ");
  Serial.print(bytes);
  Serial.print(" of information\n");
  for(int i = 0; i< bytes; i++)
  {
    x = Wire.read();
    Serial.print("Slave Sent: ");
    Serial.print(x, HEX);
    Serial.print("\n");
  }
  delay(500);
}

Slave Code

#include <Wire.h>

#define SLAVE_ADDRESS 0x60
byte x = 0x00;
void setup()
{
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("Request from Master. Sending: ");
  Serial.print(x, HEX);
  Serial.print("\n");

  Wire.write(x);
}

void receiveEvent(int bytes)
{
  if(Wire.available() != 0)
  {
    for(int i = 0; i< bytes; i++)
    {
      x = Wire.read();
      Serial.print("Received: ");
      Serial.print(x, HEX);
      Serial.print("\n");
    }
  }
}


What is the difference between Tools > Board settings in Arduino IDE? ex: ESP32-Dev v. Huzzah32

For ESP32 boards the differences are very minor. In general an ESP32 is an ESP32. The only changes are name to pin mappings, and how to upload code.

There are a couple of different ESP32 modules, but in general all the boards use the same (cheapest) module.

If you look at the pins_arduino.h file for a variant you see that it is pretty much all in the format:

static const uint8_t SDA = 21;
static const uint8_t SCL = 22;

Just mapping names to pins. Note that some are special, like SDA and SCL above, which are used as defaults for the Wire library.

The biggest differences are in the boards.txt portion for the board. This is where any differences in the module will be defined.

In general though all the "specific" boards are just the "ESP32-Dev Module" with some options removed, and a new name give to it.  So you can usually use ESP32-Dev Module for any board as long as you select the right mode for things like flash.

One big benefit of using the correct board, though, is that a #define macro is provided identifying the board. If you want the same code to run differently on different boards (such as using different pins on different boards) you can use that macro to direct the flow of your code.


I have not previously met the Flexscan sensors but from the datasheet it appears that there are versions of the A201 rated at 100 pounds are you committed to the 25 lbf version?

A201 datasheet here

Here is a 15 page user manual thatexplains how to produce a voltage output using a single opamp per sensor - bottom of page 9.

Many idea starters here

What is your application and why do you wish to use these sensors. These seem to be a low accuracy alternative to eg load cells and seem to be expensive for what you get. If you need 8 for your task a loadcell based solution may e cheaper.


How do you use the plastic cover/case that came with Arduino?

The cover was developed for Arduinos with on-board Ethernet with POE and similar cover has the Ethernet shield with POE. POE - power over Ethernet is 48 V, so it is better to not to touch a soldering point with this voltage.

The arduino.org boards were sold with this cover. Some of them had on-board esp8266 and soldering points leading to esp8266 sensitive pins. Again, better not to touch.

I used the cover to attach the Arduino to a DIN rail over a DIN rail clip.


How to detect V-SYNC on the SparkFun MicroView?

The scenario you describe is called the Tear Effect. On the SSD1306, which the device you are interested in is based around, a Frame Synchronisation pulse can be emitted on the FR pin.

However it would appear that the specific SSD in use by SparkFun does not provide this pin from the SSD1306 on the external FPC connector, so there is no way of getting it.  Probably owing to the small size of the display a reduced size connector without extra pins like FR was used.

So no, you can't combat the Tear Effect with that display.

There is nothing you can do over SPI, either. That is simply because SPI is just too slow for such things. You would use the FR pin because it's instantaneous.  With SPI you would have to make a request to read a register, then read that register's value back. In that time, coupled with the question of exactly when would the register say it was at the start of a frame, the information would be completely meaningless anyway.


readStringUntil('\n')
//Receiver Mega

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial1.begin(9600);
  Serial.begin(19200);
  delay(100);
}

void loop() {
  if (Serial1.available()) {
    String received = "";
    received = Serial1.readStringUntil('\n');
    Serial.println(received);
  }
}

It's about how Serial.readString() works: it reads from the serial port forever in this case. It stops reading if the serial interface is given a time-out. There are two possibilities:

use readStringUntil() on the receiver
call mySerial.setTimeout(300); (from setup()) to set a 300ms (for instance, as long as it's significantly less than 1000) time out on the receiver — it defaults to one second!


Background

The function millis () returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).

See: http://arduino.cc/en/Reference/Millis

Example:

unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.

Computing this in terms of days we have:

2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

Is this bad?

No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.

Let's clear up some misconceptions:

The processor does not reset when the timer overflows.
The timer does not stop.
Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

How do I time an event?

There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, subtracting is the correct way.

Example of adding - not recommended!

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long whenToStop = startTime + 60000;

...

if (millis () >= whenToStop)
  {
  // do something
  }

This will work most of the time, but not when the timer overflows. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:

2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

Example of subtracting - recommended

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

This will work all the time. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of 0xFF0000C350. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.

Demo using the Mac Calculator app:

In 60 seconds the timer goes to 10000. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.

Directly after we set up startTime and millis we will see a sequence like this:

millis ()   -  startTime    =  difference
                             (modulo 2^32)
4294917296     4294917296               0  <-- we start timing here
4294917297     4294917296               1
4294917298     4294917296               2
...
4294967295     4294917296           49999  <-- largest unsigned long value
         0     4294917296           50000  <-- wraps here back to zero
         1     4294917296           50001  <-- keeps counting up
...
      9999     4294917296           59999
     10000     4294917296           60000  <-- time's up!

Recommended method

Use unsigned long (not just long) for "time" variables.
Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
Subtract the start time from the time now, giving a difference.
See if the difference exceeds the desired interval.

eg.

startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }

Can't I just reset millis?

You can, but you don't need to. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

What about micros?

The function micros() returns the number of microseconds since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.

 2^32 / 1000 / 1000 / 60  = 71.58 minutes

http://arduino.cc/en/Reference/Micros

However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.

Also be aware that the resolution of micros() is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

Limitations

If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

Reference

This answer taken from my page http://www.gammon.com.au/millis


Esp8266 server unreachable. Port doesn't open

The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133


Digital Input using a button doesn't work properly when using it to control a relay

You have to invalidate the ‘state’ variable when Serial is not available, otherwise you will produce strange behaviours.

if(Serial1.available() > 0){
       state = Serial1.read();
  } else {
       state =-1; // not valid
    }

Also, you have to check ‘1’ and ‘0’ characters and not 1 and 0 values. ‘if (state == ‘1’)..’


Rule #1 9V batteries a power supply they are NOT. In your case you are looking at small voltages for the motor power. Your choice of a driver is not the best as you will have from 1.2 to 2.4 volts across the L298 depending on the loading. This is directly from the ST data sheet. Try the TB6612FNG instead, taking advantage of the device’s use of MOSFETs. The TB6612 may be a little more expensive, but it will be clearly worth it.


How does Arduino IDE for mac deal with functions in other files

arduino has its own little .ino preprocessor that generates forward declarations (like in a header file) for all function in the project's .ino files. Most of the time this just makes things less confusing for new users.

I'm not familiar with the entire process, but the effect is that any function in any .ino is known to all other .ino code.

Anything with .h or .cpp in a library or in the project file is treated as normal c++ code and not subject to arduino's manipulations. It will need "#include"s.

If you are interested, there is a hack to make arduino not mess with a function in a .ino file: add an empty "throw()" like this:

void foo() throw() {
}


NRF24L01+ changing configuration after startListening

The first thing that comes to my mind is that you are powering the nrf24L01 directly from the 3V3 pin of your Arduino Uno. DO NOT do this.

The 3V3 pin does not provide enough current for the nrf24L01. This renders the module completely unstable. You can:

Use a decent capacitor across the VCC and GND on the module. (But I do not recommend going for that solution)
Use a separate 3V3 power source that is capable of handling the current spikes of the nrf24L01. But don't forget to connect its ground to the Ardino Uno aswell.
Use a power module that powers the nrf24L01 from Arduino Unos 5V rail.


No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.


Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer?

Thank you to all who have suggested corrective action for my posted communication problem.  After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor.  Next I installed the Arduino Create Editor as a fresh/new install.  Magically, all of my communication issues with the Arduino Uno have been corrected.  Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


Same code in setup() and loop() give different results

After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

There was some initial confusion (see the edits) where the hasBeenSet flag was initialized the wrong way around.
I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
Possibly faulty WS2812 chip - try with another one.
Possibly faulty Arduino - try with another one.
Possibly Arduino running at the wrong clock speed which would throw the timings out.
Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
Possible bug in the library. We eliminated that by trying with my library for Neopixels.

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.

We never really worked out why doing it in loop rather than setup made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.

I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.


Strange characters after typing an AT command in serial monitor

for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :

GPRS.begin(2400);
Serial.begin(9600);

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere

GPRS.begin(2400);
    Serial.begin(2400);

and don't forget to change also  the speed on the serial monitor to 2400
I hope this will help someone


The problem was solved by:

making a clean install of Arduino IDE 1.6.9
uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.


The compiler cannot detect a missing ISR since it is very difficult, in
the general case, to tell whether any particular interrupt-enable bit
has been set by the program.

The avr-libc library does indeed provide a “catch-all” ISR and, as
stated by the manual,

  the default action is to reset the device by jumping to the reset
  vector.

If you don't like this behavior, you can override this catch-all with
your own, as explained in the manual (search for “Catch-all
interrupt vector”).


arduino resets or hangs after providing power to DHT22

The sensor is a large capacitive load. You need to improve decoupling of the CPU power supply.

A 10 uF between 5V and GND will help for the current spike and the resistor in series with the sensor will not be an issue (50 uA on 250 Ohm makes only 12.5 mV voltage drop once the sensor is started).


Briefly "wake up" Arduino in response to an event

Easy answer: Don't.

Have the Arduino sleep most of the time, and let the door handle invoke an interrupt that wakes it up. Then do whatever processing is required, and then go back to sleep.

This won't work as well with a full Arduino as it would with a bare MCU since the rest of the board has its own quiescent load, but once you get it working with an Arduino you can get a bare MCU, wire it up, write the code to it, and away you go.


Arduino sketch taking forever to upload, followed by multiple issues

When the Arduino IDE says its uploading but never uploads, it is most likely a COM port issue. Try plugging the Arduino in a different port and make sure you change the port in the IDE. The problem seems to be you have changed the Arduino port, but not in the IDE. The Arduino IDE registers the previous port as open and tries to upload the program to that port. Go to Tools > Serial Port and it should list the ports(example):

COM 2
COM 3
Arduino Uno at COM 4
•COM 4

Every time you unplug and replug the Arduino you should check your ports and select the appropriate one ( It usually says Arduino *type* at COM *port number*

COM 2
COM 3
•Arduino Uno at COM 4
COM 5


Benefits of STK500? Sure:
- It has push buttons
- It has LEDs
- It has easy accessible connectors to any controller pin

Actually that's all. If you want/need to make use of this, buy both. Use the STK for "rapid prototyping" and the Dragon for debugging.
But if your budget allows it, have a look at the STK600 instead of 500. It's more expensive, but not so "old-fashioned", and it has much more features.


How I could make a bus connection in a prototype shield?

I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.

A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.

https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ%2beHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0


Share battery pack with Arduino and DC motors

You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts.

As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower.  A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used.

Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack.  Not a lot to lose on trying.

The UNO already has decoupling capacitors in it's 5 volt regulator circuit.

Just for fun,  you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator.

If you decide to measure the 5 volts with an analog input,  read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.


With stepper motors you don't need any form of encoder. Only a limit switch.

A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.

If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.

All you need to do is count.


The condition HIT_CENTER || HIT_RIGHT || HIT_LEFT will always be true.  (All three of those HIT_ values are non-zero constants.)

Instead, you need to test if getHit() is non-zero.  (To see this, search the sketch for occurrences of HIT_RIGHT or HIT_LEFT.)

The sketch sets up an event timer (via ball_timer = timer.every(BALL_DELAY, moveBall); in setup()) so that ball position will update every 200 ms.  The loop() sequence is: Use timer.update() to service timer events.  Use setPad() to read the paddle position.  Use drawGame() to update the game picture. Somehow use checkLoose() to see if game is over.  Use delay(GAME_DELAY) to wait 10 ms.

Given that structure of loop(), throwing in a 100 ms delay to wait for a buzzer would mess up the game play.  You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.

More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before delay(GAME_DELAY), and always turn the buzzer off just after that delay.  In other words, before the delay say:
if (getHit()) digitalWrite(buz, HIGH); and after the delay say digitalWrite(buz, LOW);.

This supposes that writing HIGH to buz turns on the buzzer and that writing LOW turns it off.


Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors

I have run into similar weirdness myself, and the solution that worked for me is to have separate batteries for the Arduino and the motors. This is more important if your motors run at a different voltage (e.g. 6v or 12v motors), but is useful in any case. This means that, when the motors draw to much from the batteries, the motors will slow down. If the same battery is used for the motors as for the Arduino, then the voltage drop from the motors will also apply to the Arduino; if the voltage drops in the Arduino, it will turn off (and turn back on when the voltage is restored). This is likely what you are seeing.


Do multiple ultrasonic sensors need an external power source?

Well, according to the datasheet the "working current" is 15mA.  Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.

The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored.  Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors.  Most of the current consumption would be while you are actively producing an ultrasonic chirp.

So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.


Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper

There are many ways to do this. The master could be the central unit which makes all the decisions, or the slave could preprocess the information.

It is best to start with a single byte to make it work. But I have made examples for two bytes anyway.

The next examples requests two buttons via i2c. You can change the HIGH and LOW into an integer value, but this is a start to make it work.

Master (without checking)

void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  int button1 = Wire.read();
  int button2 = Wire.read();

  Serial.print("button1=");
  Serial.println(button1 == HIGH ? "HIGH" : "LOW");

  Serial.print("button2=");
  Serial.println(button2 == HIGH ? "HIGH" : "LOW");

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Master (with checking)

void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  if(Wire.available() == 2)   // are 2 bytes received ?
  {
    int button1 = Wire.read();
    int button2 = Wire.read();

    Serial.print("button1=");
    Serial.println(button1 == HIGH ? "HIGH" : "LOW");

    Serial.print("button2=");
    Serial.println(button2 == HIGH ? "HIGH" : "LOW");
  }
  else
  {
    Serial.println("The slave was not found");
  }

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Slave (very simple)

void requestEvent()
{
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  Wire.write( (byte) buttonState1);
  Wire.write( (byte) buttonState2);
}

Slave (advanced, update button state in the loop)

#include <Wire.h>

const int button1Pin = 2;
const int button2Pin = 3;

// Variables that are used in a interrupt and also outside
// that interrupt must be declared as volatile.
// Then the compiler knows that they can change at any moment.
volatile byte buttonState1;
volatile byte buttonState2;

void setup()
{
  pinMode(button1Pin,INPUT);
  pinMode(button2Pin,INPUT);
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
  // keep the variables updated with the latest information.
  buttonState1 = (byte) digitalRead(button1Pin);
  buttonState2 = (byte) digitalRead(button2Pin);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  // send the two bytes.
  Wire.write(buttonState1);
  Wire.write(buttonState2);
}


Display upTime using `millis()` - Arduino Uno

The millis function increments rapidly, hence it easily exceeds the maximum value of int -  -32768 to +32767.
So, use unsigned long data types for millis and other stuff that's large.
4 billion and some change is the max value that unsigned long data types can store, hence no overflowing till about 49 days.


i am having Strange issues when trying to read form gps serial connection

You are not reading the GPS often enough. The method
Adafruit_GPS::read() is documented in the comments embedded in the
source code:

  Read one character from the GPS device.

  Call very frequently and multiple times per opportunity or the buffer
  may overflow if there are frequent NMEA sentences. An 82 character
  NMEA sentence 10 times per second will require 820 calls per second,
  and once a loop() may not be enough. Check for newNMEAreceived() after
  at least every 10 calls, or you may miss some short sentences.

  returns: The character that we received, or 0 if nothing was available

Accessing the I2C bus makes loop() slower, slow enough that you get a
buffer overflow, as explained above. I suggest that, instead of reading
a single character per loop iteration, you read as many as are present
in the buffer:

void loop()
{
    GetTotalPressure();

    // Empty the GPS port receive buffer.
    while (GPS.available()) {
        char c = GPS.read();
        Serial.print(c);
    }

    // Parse any newly received NMEA sentence.
    if (GPS.newNMEAreceived()) {  // clears the newNMEAreceived flag
        if (!GPS.parse(GPS.lastNMEA()))
            return;
    }

    // Display and log location every second.
    if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
        GPSScreenUpdate();
        SDcardSave();
    }
}

As an aside, I removed the line

if (timer2 > millis()) timer2 = millis();

which serves no useful purpose. If you are trying to detect millis()
overflows, you are almost certainly doing something wrong.


ESP8266 ASCII to HEX convertion and checking

A little explanation about HEX and ASCII:

About HEX
Raw computer data consists of zeros and ones. For humans it is difficult to read a (long) row of zeros and ones. You can represent such a row (of a certain length) by a decimal number, but then the relation with the underlying bits is not directly clear. For this reason the hexadecimal (HEX) representation is used (hexadeca comes from Greek and means 16.
Four bits can represent 16 different situations (= 16 different combinations of zeros and ones). The HEX digit belonging to each combination is:
0000 = 0; 0001 = 1; 0010 = 2; 0011 = 3; 0100 = 4; 0101 = 5; 0110 = 6; 0111 = 7
1000 = 8; 1001 = 9; 1010 = A; 1011 = B; 1100 = C; 1101 = D; 1110 = E; 1111 = F
When you memorize these 16 cases (from which the first 10 are easy because it is juist binary counting), you know immediately which bit-pattern belongs to a hexadecimal number and vice versa. For example: the HEX value 5A = 01011010.

About ASCII
Computer data contain not only numbers, but also text. As the computer can only handle bits (zeros and/or ones) we have to decide how letters (characters) are presented by bit patterns. And preferably in a standardized way, in order that different computers can handle each others text. Unfortunately there is more than one standard, but one that is very much used is the ASCII standard (see: https://en.wikipedia.org/wiki/ASCII).
The ASCII standard uses 7 bits codes and defines not only characters but also 'control codes' e.g. for 'line feed' and 'carriage return'. Often these 7 bits are stored in one byte (with the leftmost 8th bit set to 0) and can than be represented by two HEX digits.

Without further information nobody can tell what a row of bits represents. That's one of the reasons datatypes are used. They tell us what the row of bits represents and how many bits (or bytes) are used for the representation.

So the HEX representation of your row of 3 bytes is "1B 42 05" and, when these are characters, could stand for (look at the ASCII table): "ESCAPE B ENQ". In which 'ESCAPE' and 'ENQ' are control codes which meaning depends on the communication protocol.
The second row (of 14 bytes) could stand for: "STX SPACE - 3 0 2 5 0 SPACE k g CR LF ETX". STX and ETX stand for 'START OF TEXT' and 'END OF TEXT'. 'LF' stands for 'LINE FEED' and 'CR'stands for 'CARRIAGE RETURN'.

I hope that with this explanation you have a better idea about HEX and ASCII and that you now will be able to figure out how to handle your data.


How can I reduce the memory usage on my code?

As well as PROGMEM (as described in the comments), there are a couple of other efficiencies that you can make:

A function call is expensive (takes a lot of code space), and you are performing a LOT of them!

The repetitious calls to delay() followed by treeFunc() are wasteful. Your commented-out line

//delay(arrayTimes[i]);

looks like you were going to do the right thing, so I’d restore that (use count instead of i) and put the delay() numbers in a new int arrayTimes[] array.

PROGMEM this array too, of course!
Once you’ve done this, you can remove all the calls to delay(). You’ll be left with nothing but repeated calls to treefunc(), which you can replace with a single loop:

for (count=0;count<sizeof(arrayTree);++count) {
   treeFunc();
} // for

Don’t forget to get rid of the count = count + 1; line from treeFunc() - it’s now in the for loop.

Also expensive is calling the same function twice except with different parameters in both sides of the if in treeFunc(). Instead of:

if (<condition>) {
   Function(1);
} // if
else {
   Function(0);
} // else

you can instead do:

Function(<condition>);

For this to work, you need to know that HIGH has the value 1 and LOW has the value 0 - and that a true condition has the value 1 and a false condition has the value 0.

So, you need to change the if () slightly:

digitalWrite(THREEONE, (num%2)>0);

Finally, the mod % operator itself is very expensive, since it is effectively a division, and the Arduino chip doesn’t know how to divide - so the code to do so is large. But the code you’ve written is using binary arithmetic, which the Arduino can do instantly - you just have to write it as such.

Instead of (num%2)>0 use num & B0001.
Instead of (num%4)>1 use num & B0010.
Instead of (num%8)>3 use num & B0100.
Instead of (num%16)>7 use num & B1000.

You’ve probably copied the guts of this code from somewhere else, and while it works it isn’t very efficient. Writing the code as above will greatly reduce your code size, exchanging repeated calls for much smaller PROGMEM arrays.


inconsistent digital output on simple code

If I look at the first 5 lines:
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);

You see that pinModeout, OUTPUT)uses a variableoutwhich is not initialized (it's only declared inint out`'.
I assume D3 to D8 are all output pins, so you have to replace the last line with:
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(D5, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
pinMode(D8, OUTPUT);

Also, since you are using all pins in the same way, I suggest you use two variables: startPin and endPin. Then you can use a for loop to iterate through all pins. Also

always initialize variables.
use '0' instead of 48 when you convert from a byte value to a character (since you don't need to know the ASCII value of '0').

I don't have an Arduino compiler at hand, but it should look something like:
byte b = 0;
int out = 0;
const byte startPin = 3;
const byte endPin = 8;

void setup() {
  Serial.begin(9600);
  for (byte pin = startPin; pin <= endPin; pin++)
  {
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
  }
}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - '0';
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);

  ...

However, from here you are using the pins as INPUT pins. You cannot change those on the fly, you might change them manually (by using pinMode(pin, INPUT)), but it does not seem normal to switch input and output pins, so maybe you should explain what you are intending with your application.


Use doorbell output (12VDC) to power arduino?

This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.

The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.

Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.

The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.

So what's the easiest way to accomplish your task?

Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.

You need to replace/augment the LED on the ringer with the Arduino. The 2.2k R19 could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.

The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit  pulls all the current out from under the LED, just as it will an MCU in the same slot.

You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.

So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.

Good luck; sounds like a fun project and a good challenge.

EDIT:
I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...


It is just so obvious that you should connect them that they did not bother to write it down.

The reader needs power. That is taken as read. Without power it can do nothing. Why would they bother to waste time telling you to connect the things that you have to connect regardless? The only things that they tell you to connect are things that are specific to the sketch - i.e., which IO pins to connect to which function on the reader. Power doesn't change - it's the same from sketch to sketch and from person to person. The IO pins do, though, and need to be detailed. Power and ground don't.


What is the smallest microcontroller capable of running Arduino?

Well, your questions is quite vague and perhaps overly broad.  I'll answer your main question "what is the smallest," assuming you meant dimensionally, while keeping in mind that you also want the most powerful one in that size. The pricing of different chips like this will be fairly similar so I'll ignore that.

Next, I'm not sure what you meant by saying "capable of running Arduino" which may mean capable of having the Arduino bootloader installed or could mean being capable of running code written with Arduino libraries.  I'll assume the latter since it's the most practical requirement. I'll also assume you want an Atmel chip since it will be the most directly compatible with the Arduino libraries.

So what is the most powerful of the smallest Atmel microcontrollers capable of running Arduino code?

The answer is probably the Attiny 10 which comes in a 2 x 2mm 8-UFDFN Exposed Pad package, or a 2.9 x 1.6mm SOT-23-6 package for about one dollar in small quantities.

Also see this Hackaday article on how to use the Attiny10 with Arduino.

Edit: After more research, I was unable to find an Arduino core for the Tiny10. So while you can program it with an Arduino using assembly or something, writing Arduino code for it won't work.  The smallest Attiny with an Arduino core I could easily find is the Attiny13 in a 3 x 3mm 10-VFDFN package.  The upside is that while not being that much bigger or more expensive, it's a way more capable chip for your project.


Can we have 2 HC12 on a single Arduino (1 to receive and other to transmit)?

Yes you can - one on Serial pins 0/1 and the other using SoftwareSerial on any other pins. Note that the one on SoftwareSerial will interfere with the one on Serial as it disables interrupts while sending or receiving.
It may be better to use an Arduino which has multiple hardware serial ports. Maybe one of the Teensy boards would be better for your needs.
Alternatively if (and I am not familiar with the modules enough to know if this is right or not) they operate as a transparent serial bridge then you could connect one module to the TX pin for transmission and the other to the RX pin for reception - reading from serial receives from one, and writing to serial transmits through the other.
Also note that you will have to ensure that both pairs of modules are running on different channels to prevent interference between them.


What is the best way to make a good but simple line follower?

Did you check wikipedia, for example?

I doubt it is possible to describe a PID controller in simpler words than those used by the article.

The pseudocode is quite simple and should be also very good for understanding the concept, when applied to a digital system.

See also the limitations of PID controllers.


You can use the library for IDE 1.6 https://github.com/damellis/attiny/


HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.


WDT & Software RESET in ESP8266 + Arduino IDE

Software reset in ESP8266 is achieved using ESP.reset()

as per WDT, the other answer has info on that, i.e. software WDT is cleared using yield() - hardware WDT is not accessible through software


Speed calculation in most GPS systems is very crude. It consists of simply "Where was I then? Where am I now?". Many will also add "How long has passed between then and now?", but many also don't - they assume a fixed time between points (1 second, for example). It doesn't know it's supposed to move, all it knows is the coordinates it has at the moment.

With the latter, if you don't get a reading for a couple of seconds (buildings in the way, for example) the position can suddenly jump a long way.  You can see the effect in your phone's GPS in built-up areas - your position may jump long distances and then pause for a bit.

To visualise it in 1-dimension, you can think of a simple number sequence 0-9 and the difference between each value:

Value:        0 1 2 3 4 5 6 7 8 9
Difference:     1 1 1 1 1 1 1 1 1

The difference equates to the "speed" of the sequence.

Now if the numbers don't get updated smoothly, but all at once at the end, you get something like:

Value:        0 1 2 2 2 2 2 7 8 9
Difference:     1 1 0 0 0 0 5 1 1

The end results is the same, but you get a "dead" period with no "movement" and then a big jump with an unusually high speed.

It's up to you to filter out such anomalies. It's simple enough to say "5 is too much - ignore it". You could also average the past 10 seconds worth of data (for example) and use that as your average speed over that time period, which would smooth out such peaks and troughs.


Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS

I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield.

The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS.  It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield.


Seems like wrong baud-rate. Change baud-rate in the Arduino IDE serial monitor.


Why can't the Atmel ATtiny family delay over a minute?

This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.

See my page about Integer arithmetic and overflow.

To excerpt from that:

On the Arduino (Uno) platform, what do you think will be printed here?

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

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Did you guess:

60000
86400
500

Nope!

It prints:

-5536
20864
0

This is because of integer arithmetic. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

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

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Now we get:

60000
86400
500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an int and a long will result in the int being promoted to a long (regardless of whether it appears first in the expression or not). However if an int is being added to another int, it will not promote them to a long, even though the result may not fit into an int.


Like Mikael Patel said, SoftwareSerial disables interrupts for the entire character receive time.  Bad juju.

This answer lists the alternatives:

HardwareSerial is always the best.  Simply connect the device to pins 0 & 1 and use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The UNO only has Serial.  Serial would not interfere with the Servo.
AltSoftSerial is the best of the software serial libraries.  Only one instance is allowed, and it is must be used on the Input Capture pins (pins 8 & 9 for a Nano).  It would not interfere with the Servo.
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.  Receiving characters does not disable interrupts, but transmitting does (i.e., TX would interfere with the Servo).
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot transmit and receive at the same time (unlike all other choices).  This can interfere with other parts of your sketch, other device communications, or with libraries (e.g., Servo).

In your case, I would suggest connecting the HC-12 to pins 0/1 and use Serial.  No software serial library required, but you will have to disconnect pin 0 to upload new sketches over USB.  Some people put a switch in that wire so it's easy to upload a new sketch.

If you need debug prints, I would suggest using AltSoftSerial and an extra TTL Serial-to-USB adapter (aka FTDI module) to your PC.  Then print your debug messages to the AltSoftSerial variable:

#include <AltSoftSerial.h>
AltSoftSerial debugPort; // always pins 8 & 9

   ...

void loop()
{
  if (something) {
    debugPort.println( F("something happened!") );

Or, if the HC-12 connection is receive only, don't connect pin 1 (TX).  Then your debug prints won't go to the HC-12.

BTW, don't use delay and don't use String.  They will get you into trouble sooner or later.


Digispark clone not recognised when plugged in

The Digispark does not use a "standard" USB-to-Serial chip but is dependent on a special bootloader called "micronucleus" that makes it (sort of) act like a USB device.

Below is a description of the steps you need to perform for a Windows system and the Arduino IDE.

First, you will need to install a Windows driver for Micronucleus: Zadig USB driver

If your ATTiny is recognized by Windows after performing the driver installation, then all is fine and you can skip to step 4.

If Windows still does not recognize your Digispark clone, its ATTiny processor might not have come with micronucleus pre-programmed and you need to perform steps 2 and 3. Unfortunately this is for advanced users and might be difficult if you're inexperienced with electronics and/or Arduino.

Download Micronucleus from Github
Follow This tutorial from Digispark to install micronucleus on your ATTiny. You will need another Arduino (Uno, Nano, Mega, Mega2560, ... or clone) for that.
Then follow This tutorial from Digistump to enable the Arduino IDE to program your Digispark clone directly from USB.


You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.


You're using a USB to RS-232 adaptor. That is wrong.

RS-232 is not (electrically) the same as UART.  Not only is the logic inverted, but it uses ±10V NRZ signalling.

That means that when the UART expects a 3.3V HIGH signal the adapter is sending it a -10V signal. When it's expecting a 0V LOW signal it's being sent a +10V signal.

So yes, it's gibberish - it's getting the opposite of what it expects to see - and the excess and negative voltages risk damaging your ESP. Fortunately the currents involved are usually so low that it doesn't damage it straight away, but with prolonged use you can probably kiss your ESP goodbye.

Disconnect that dongle immediately and get a proper USB to UART adapter.


Is there any way to download a sketch from an Arduino?

It should be possible as long as the security bit isn't set. This question was asked on EE a while back.

Is it possible to extract code from an arduino board?

But you won't get the Arduino code you wrote back. The code is compiled into assembly and you'll have to convert that back to C yourself.


Passing class member function as argument

It's quite common question related to C++ programming.

The extensive explanation can be found here.

The short answer is: it's very different from taking the address of a regular function.

Workarounds (that might or might not work for you, depending on what else you need that function to do) are:

make it static
declare it as friend function, rather than member function

Either way, the point is that it should not be something associated to an instance of the class, but rather to the class as a whole.


It turns out it was a problem with the android terminal program i was using, by switching to another that specifically has support and options for \n \r things it works now.


How do I connect an MPU6050 sensor to an Arduino MKR WIFI 1010?

The sensor was indeed broken, and I had no problems after ordering a new one.


How to wire and use a B10K linear LED potentiometer?

The Taiwan Alpha spec sheet page 2 for this type of pot shows a little information about the pinout.  Refer to the second “P.C.B. MOUNTING HOLE DETAIL” diagram, which apparently shows the top side PCB layout.  The LED's anode is at lower right, marked B; its cathode is lower left, marked E.  It doesn't say what L (the pin next to E) is.  The three numbered pins most probably are: 1 and 3, ends of the resistive element.  2, wiper.

If that is correct, you could attach pin 1 to 5V, pin 3 to ground, and pin 2 to an analog input.  Before hooking it up like that, however, take ohmmeter readings from pin 1 to pin 2 as you move the slider from one end to the other and see if readings change proportionately to position.

Note, the phrase “Center Dent” on the ebay page probably should instead be “Center Detent” or  “Center Click”.


Reuse Makerbot SMD-2.3 Stepper Driver with Arduino

From http://reprap.org/wiki/Stepper_Motor_Driver_2.3#IDC_Connector

IDC Connector

Pin     Name    Function

N/C     Not Connected to anything
GND     Connect this to your uC to share a common ground.
Step    A pulse on this line will make the stepper motor advance one step in the desired direction.
Dir     If this pin is high, the motor will rotate forward, low it will rotate backwards.
!Enable    This pin allows you to turn the motor on and off. It is an inverted pin to avoid noise turning the driver on. By default it is disabled (pulled high). A high signal means off, low signal means on.
Min     This is the signal from the 'min' sensor. The definitions of high/low are determined by your opto endstop.
Max     This is the signal from the 'max' sensor. The definitions of high/low are determined by your opto endstop.
GND     Connect this to uC to share a common ground.
GND     Connect this to uC to share a common ground.
GND     Connect this to uC to share a common ground.


Not environment, no.

If you have access to the compilation command line you can do the equivalent of #define from there:

avr-gcc ... blah blah ... -DUseFirstDir

That is most effective if you are using a Makefile build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).

A better IDE, though, can do it. Facilities for setting control flags like that exist within UECIDE and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).

Or you can just have a list of #define options at the top of your sketch:

/* Uncomment this to use the first directory. */
// #define UseFirstDir

// .... later ....

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif


How can I stop my servo looping when my sensor doesn't detect movement?

Don't set the pos to 180 in the (digitalRead(pir) == LOW) branch if you do not want it to repeatedly jump up to 180 for as long as the condition is true.
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  myservo.write(pos);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (; pos > 0; pos -= 1) { // decay to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  Serial.print("Motion ended!");
}

Alternately, you could use pos as a state variable and simplify things:
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  elif (pos > 0 ){
     pos--;
     delay(15);
  }
  myservo.write(pos);
}


Problem with LED (Builtin) connected to pin 13

This is a normal thing. All my arduino boards do the same. The reason for this is that the micro controller don't care about the pins that aren't defined in the code. When they aren't defined they all have a HIGH on them. Here is my board with this code:

void setup() {
}
void loop() {
}


Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino

It was a strange problem which we were not able to resolve in an acceptable manner after all.

The problem disappeared after we re-flashed the device.


Arduino Uno Motor control using 2 Relays, 2 Limit switches and Bluetooth. Forward Reverse Stop

Here I am again for another exciting episode of "Fun with StateMachines".. ;)

Ok, basically you modified the code well, but you thought of the modification in the wrong way.

First of all describe what you want to do in simple words. Let's say you want that

  When I'm moving in one direction and I receive the letter 'S', I immediately stop without waiting for the endstop

Consequently, you know that

you will have to add something when you are moving in one direction
this "something" will top you, which is what the endstop does

So, to implement this, you can do something like this:

switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

Now, your second problem is a bit harder to understand. When I read it, I immediately thought what chrisl already pointed out, which is switch bounces. But when I was halfway into completing this part of the answer I found out that.. no, the bounces are not what can give problems here, unless you are constantly writing 'A' or 'B' on the serial. So for the second part of the question please post your schematic and/or photos of the setup, so we can see if there is something not normal


Different questions regarding Arduino C++ library coding style

Why they connect the variables to the class with scope-resolution operator "::"?

Those are static variables. They don't exist within an instantiated class instance since they are common to all class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

  I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

  There are three versions of the "begin" function, can someone explain why?

This is called function overloading. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

  Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other begin() function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the begin() function that takes no parameters.


Flow control between ESP32 and RS323 device

You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).
In the sample below, you just have to:

assign UART_CLIENT_RTS and UART_CLIENT_CTS to the pins of your need
change uart_config_t to whichever parameters are relevant for your RS232 device
set flow_ctrl to UART_HW_FLOWCTRL_RTS, UART_HW_FLOWCTRL_CTS, UART_HW_FLOWCTRL_CTS_RTS or UART_HW_FLOWCTRL_MAX

    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);

Communication can be done with the various uart_write_* and uart_read_* methods as defined in the documentation.


I don't know what that adapter is (a link would be nice, or at least the chip number it uses) but in general the 3.3v on a USB TTL adapter can only provide a small current. For instance the FT232RL can only provide up to 50mA at 3.3v. That may not be enough current to drive the RF circuitry of the ESP. The early Arduinos used the FT232RL chip for the USB interface and it was the 3.3v from that which was used for the 3.3v header on the Arduino. This was somewhat of a failing with those Arduinos since the 50mA limit was a real problem when people started using more 3.3v devices. That was one of the driving forces (as well as cost) in the decision to switch to an MCU for the USB interface.

So to be on the safe side I wouldn't use the 3.3v from the USB adapter to power the ESP. You are better using a 5v to 3.3v regulator circuit driven from the 5v of the USB. And yes, that could be a whole Arduino, or build your own on some stripboard.


Error using Crypto Library for Arduino: Speck

byte cipher[16]; declares cipher as an array of 16 bytes.  As such, cipher has no methods, much less ones called setKey() or encryptBlock().

Note, setKey() and encryptBlock() look like method names one would find in Crypto or Speck library code; however, I don't find them in the Crypto and Speck headers I looked at on github sites.  Also, buffer, cipher, and keySize look like variables and parameters one would use in creating an object for use with encryption methods.

In short, it appears your code fails to set up an appropriate class of objects that have setKey() and encryptBlock() methods.

Note, while I am not familiar with their details, I question whether all of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h should be included in your code.  It seems more likely that you would choose one of them as appropriate to your needs.

Edit 1:  Looking at TestSpeck.ino as mentioned in per1234 6's comment, one sees a function perfCipher(), with its first argument declared as BlockCipher *cipher.  That is, cipher is declared as an object of a class that has setKey() and encryptBlock() methods.

The TestSpeck.ino sketch includes all three of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h because it runs performance tests that compare results using different Speck implementations.  In practice you usually won't need more than one of those headers.


Arduino Uno & ESP32 communication using RS485

Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.


How do you make a Class variable array bigger?

I want to [...] allow the user to program as many outputs as they want

This may be problematic. The microcontroller has a limited amount of
RAM: it will not be able to store arbitrarily long macros. You should
consider a way of telling the user “sorry, no more memory”. Or you can
be optimistic and assume the user will never try to record macros long
enough to exhaust the memory... and let the firmware crash if this
assumption turns out to be invalid.

  I currently use the String class and decode within the program but
  it's cpu intensive and not very practical.

CPU intensive? You mean the allocation? Reading the contents of a String
object is not CPU intensive. And what do you find impractical in the
String class? At it's core, it's just a dynamically sized container for
character data, which seems to be exactly what you are looking for.

  I haven't found any way to expand the size of an array inside a class.

A class is a data structure of fixed size. There is no way you can
expand its contents. If you need something of variable size, you will
have to use dynamic allocation. You will then only store a pointer to
the allocated memory in your class. This is exactly what String does.
The only other option is to store an array of fixed size within the
class, and make that size large enough so that you never need more.


It looks like you are not telling PlatformIO that you need the JC_Button library. Try adding this to your platformio.ini file:

lib_deps = https://github.com/JChristensen/JC_Button


I got it working using the code below:

#include "SoftwareSerial.h"
String ssid ="Home";

String password="%Qwerty@123%";
char input[12];
int count = 0;
SoftwareSerial esp(2, 3);// RX, TX

String data;

String server = "192.168.0.182"; // www.example.com

String uri = "/testget.php";// our example is /esppost.php

int DHpin = 0;//sensor pin

byte dat [12];

String temp;

void setup() {

pinMode (DHpin, OUTPUT);

esp.begin(9600);

Serial.begin(9600);

reset();

connectWifi();

}

//reset the esp8266 module

void reset() {

esp.println("AT+RST");

delay(1000);

if(esp.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network

void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";

esp.println(cmd);

delay(4000);
}

byte read_data () {

byte data;

for (int i = 0; i < 8; i ++) {

if (digitalRead (DHpin) == LOW) {

while (digitalRead (DHpin) == LOW); // wait for 50us

delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'

if (digitalRead (DHpin) == HIGH){

data |= (1 << (7-i)); // high front and low in the post
 }
while (digitalRead (DHpin) == HIGH);

// data '1 ', wait for the next one receiver

}

} return data; }

void start_test () {

digitalWrite (DHpin, LOW); // bus down, send start signal

delay (30); // delay greater than 18ms, so DHT11 start signal can be detected

digitalWrite (DHpin, HIGH);

delayMicroseconds (40); // Wait for DHT11 response

pinMode (DHpin, INPUT);

while (digitalRead (DHpin) == HIGH);

delayMicroseconds (80);

// DHT11 response, pulled the bus 80us

if (digitalRead (DHpin) == LOW);

delayMicroseconds (80);
while(count<12){
input[count] = Serial.read(); // Read 1 Byte of data and store it in the input[] variable
      count++;          // increment counter
      delay(5);}
// DHT11 80us after the bus pulled to start sending data

//for (int i = 0; i < 4; i ++)

// receive temperature and humidity data, the parity bit is not considered
/*for(int x=0;x<12;x++)
for(int i=0;i<12;i++)
//dat[i] = read_data ();
dat[x]=input[i];*/

pinMode (DHpin, OUTPUT);

digitalWrite (DHpin, HIGH);

// send data once after releasing the bus, wait for the host to open the next Start signal

}

void loop () {

start_test ();

    count = 0;      // Reset the counter to zero
    temp = "";
    // convert the bit data to string form
for(int i=0;i<13;i++)
temp += input[i];
Serial.println(temp);
//Serial.println(temp);

data = "tag=" + temp;// data sent must be under this form //name1=value1&name2=value2.

httppost();

delay(200);

}

void httppost () {

esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

if( esp.find("OK")) {

Serial.println("TCP connection ready");

} delay(100);

String postRequest =

"POST " + uri + " HTTP/1.0\r\n" +

"Host: " + server + "\r\n" +

"Accept: *" + "/" + "*\r\n" +

"Content-Length: " + data.length() + "\r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"\r\n" + data;

String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

esp.print(sendCmd);

esp.println(postRequest.length() );

delay(500);

if(esp.find(">")) { Serial.println("Sending.."); esp.print(postRequest);

if( esp.find("SEND OK")) { Serial.println("Packet sent");

//while (esp.available()) {

//String tmpResp = esp.readString();

//Serial.println(tmpResp);

//}

// close the connection

esp.println("AT+CIPCLOSE");

}

}}


Enabling keyboard feature on Arduino with CH340G

No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.


You're using the String (upper-case 'S') functions, which allocate and de-allocate memory, a limited commodity, even with 64K. The standard heap management functions will tend to fragment the heap into pieces too small for further use. That can make new allocations slower because the heap has to be searched for a big-enough piece, and can eventually make it the heap grow toward the stack, until a collision (something gets overwritten) inevitable. We can't say for sure that this is your problem; we don't have enough information.

But try allocating one or a few buffers large enough for the worst case requirement, and use the C string functions instead (lower-case 's'), sprintf(), strcpy(), strcat(), etc. instead.


Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)

They're not defined. If you notice that whole block is wrapped in a #ifdef which will be false unless you're on some specific platform, where the platform defines those macros.

Everything else uses the last little bit:

pinMode(_txPin, OUTPUT);
pinMode(_rxPin, INPUT);
pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).


Arduino digital pin reading string numbers

From the official Arduino site, See DigitalWrite :

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

The exact definitions can be found here for reading a signal: Constants

When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.

HIGH

The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:

-a voltage greater than 3.0V is present at the pin (5V boards);
-a voltage greater than 2.0V is present at the pin (3.3V boards);

A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT_PULLUP works and is described below in more detail.

When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at:
-5 volts (5V boards);
-3.3 volts (3.3V boards);

In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.

LOW

The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report LOW if:

-a voltage less than 1.5V is present at the pin (5V boards);

-a voltage less than 1.0V (Approx) is present at the pin (3.3V boards);

When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).

Probably, HIGH is 1, LOW is 0, and ON is 1, OFF is 0.
Than 1 is mapped to 5V or 3.3V depending on the Arduino and 0 is mapped to 0V.
These mappings and the definitions of HIGH/LOW/ON/OFF are in the Arduino libraries.


Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with

The datasheet describes the electrical and clock requirements of the chip, and AVR042 describes the external hardware configuration required. Decoupling, analog voltages, external crystal or oscillator if required.


== has higher precedence than &, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a specific value, just if the appropriate bit is set.


Can stackable Arduino headers be automatically soldered?

I would suggest using SMD headers on one side and through hole on the other side. One side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/partdetails.aspx?Class=ASSMANN&ClsID=/F_ASSMANN/ASSMANN.010/ASSMANN.010.170/&PartID=10-18062010-079808
and one side with this: http://www.tracepartsonline.net/(S(30y0dp21y1rd0u3erv1mrrbw))/PartDetails.aspx?Class=ASSMANN&clsid=/F_ASSMANN/ASSMANN.010/ASSMANN.010.170/&ManID=ASSMANN&PartFamilyID=10-23062010-067691&PartID=10-23062010-067691&SrchRsltId=1&SrchRsltType=0

You will shift upper side a few mm from bottom side, and use glue to have upper side set in place and then reflow for soldering on both sides.


reversing a micro motor by reversing two pins - one Source and one sink?

**Required:**

Drive micro-motor directly from two processor pins.

 - Pin 1 high / Pin 2 low for one direction.
 - Pin 1 low / Pin 2 high for other direction.**

This is not a very good idea if it can be avoided but yes, you can operate a motor that way,  providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.

Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available.

A danger is that motor noise may affect the processor.
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.
The series resistors will drop some voltage and so are limited in maximum allowable size.
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.

Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise.

Ask further if any idea here sounds useful.

Added: Had a discussion with Gerben (below).
I'd avoided mentioning "catch diodes" but this is an add on that can help.
From each pin add a small Schottky diode* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.
(ie Cathode goes to Vcc = line on diode on upper diodes.
Anode goes to ground on "lower" diodes. )
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before  the internal protection diodes do. This is not ideal but can help.
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method.

eg BAT54 surface mount,   BAT48 through hole, 1N581x  or similar.


First: Use the ino.hex file instead of the  .ELF file
Second: this error is showing because you are compiling your code with a different board. Make sure you are using the correct board over at the Arduino IDE. My advice is: switch your board to Arduino Uno both in proteus and over at the Arduino IDE and see if it works. Later on, you can try different boards.


Googling some of those terms (especially "prog_uint16_t bitrate_table"), it looks like you may have an old version of the library, since that code was removed back in 2012.

This appears to be the latest version: https://github.com/madsci1016/Sparkfun-MP3-Player-Shield-Arduino-Library

I would start by grabbing that (using the "Download ZIP" button if you don't use git/GitHub) and trying the example from there. The examples are within the SFEMP3Shield folder.


5V DC Mini Water Pump with Arduino Mega 2560?

Welcome to arduino.stackexchange.com .

As motor is usually a high current load, controlling a switch to control the motor's power is the solution.

If you are not interested in h/w design just want to use a interface out of box you can use relay module like this relay. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.

see this answer for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.

Here is a possible schematic.

simulate this circuit – Schematic created using CircuitLab

Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.

node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.

Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic

Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

Ibe = (current gain at saturation)*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)

Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

Vce(max)(max) > VL
Ice(max) > IL
Arduino digital pin max I > Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.


To know the state of USB (Serial) connection (connected or not connected)

The problem here is twofold.

Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not.  That information simply isn't there. The main chip just receives UART serial data (not USB data) as it arrives and that is that.

Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no proper way to know if the port has been opened or not.  The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really).  The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream.  It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.

To check the status of those lines in your sketch you can examine the boolean operator of the Serial object:

if (Serial) {
  // I am connected
} else {
  // I am not connected
}

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a connection in UART terminology, only data.


My serial Monitor of the Arduino ide does not show up when running Gui?

The problem is simple, you are dealing PySerial using the serial communication port arduino, so you can not communicate with Arduino IDE and python at the same time.

Solution:

In the program you should print python q values you need, with the Print command, so you'll see in the CMD same as you see in the Arduino serial monitor.


Looking at the PDF for the Adafruit GPS shield, pin 7 is indeed hard wired to Rx and pin 8 is hard wired to Tx.

These can not be changed.

Looking at the guide for the Arduino GSM shield pin 7 is indeed reserved for modem reset:

  Digital pins 2, 3 and 7 are reserved for communication between the
  Arduino and modem and cannot be used by your sketches. Communication
  between the moden and Arduino is handled by the Software Serial
  library on pins 2 and 3. Pin 7 is used for the modem reset.

As this is the case, should you stack the two shields together, without modification, then the overlap of the Rx pin on the GPS shield will cause resets to the modem on the GSM shield.

So, it seems that your best option is to use the solution provided by RedGrittyBrick, to your previous question Arduino shield stacking, the Go-Between Shield

  You hear it all the time in the Arduino community, “will this shield
  work with my other shield?.” I think we’ve all been disappointed to
  find that two of our favorite shields compete for control of a digital
  pin here or a serial pin there. While there are sometimes some clever
  workarounds from elegant code modifications to aggressive
  ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution
  thus far: The Go-Between Shield.

Once you have used the Go-Between shield to reassign the Rx pin to something that the GSM shield does not use, (as 2, 3 and 7 are already used, let's say you use pin 6), then in the File -> Examples -> Adafruit_GPS -> Parsing sketch, you will need to change the line

SoftwareSerial mySerial(3,2);

to

SoftwareSerial mySerial(8,6);

instead of

SoftwareSerial mySerial(8,7);

which is recommended in the PDF.

I hope that this answers your question(s). Let us know how you get on.

Addenum

The schematic of the Arduino GSM shield:

The schematic of the Adafruit GPS shield:


Any time String is involved F() becomes pointless. Avoid String like the plague if you value your memory integrity.


Can't create a RTC_DATA_ATTR var inside a class

You can't put an RTC_DATA_ATTR qualified variable inside a class because the class is stored in normal RAM. The RTC_DATA_ATTR qualified variable is, by definition, stored in RTC RAM.

The definition of RTC_DATA_ATTR includes a section attribute (__attribute__((section(".rtc.data")))) that tells the compiler where abouts in memory the variable should be stored (in this case the 8kiB of "slow" RTC memory). That is mutually exclusive with where the compiler decides to store the class.

It's like you have a diamond necklace which the has to be kept in a safe at all times, but you want to wear it around your neck whilst at the same time storing it in the safe. You can't do it.


I have located the source of the problem.

In file wiring.c (arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino) which gets called before setup(), there is the following part that tries to changes the timer 2 prescaller to 64 by setting the CS22 bit.

// set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

You already set CS20 and  CS22 so this doesn't affect you. What does affect you is the following part which sets bit WGM20

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

and you have already set WGM21 so WGM21 and WGM20 set changes the timer mode to fast PWM , top=0xFF which gives almost double delay that the mode you were trying to use (CTC top=124).

How to workaround this issue?

Timer2 is used when its associated PWM pins are used with an analogWrite() call, so the Arduino setup code sets all prescalers to well-defined values just in case the timers might get used later.

I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate setup() method in your Timer class and calling that from the global setup() routine.


How to create an inverted PWM on the Due via software

Not using the Arduino API, no. But you can by direct manipulation of the SAM3X8E registers.

You should study section 38 of the datasheet, where it mentions in the list of facilities:

  Independent Complementary Outputs with 12-bit Dead-Time Generator (Also Called Dead-Band or Non-Overlapping Time) for Each Channel


ESP8266 OTA update with different flash size settings?

The basic problem is that when you upload over OTA you don't upload the partition structure.
The ESP32's flash is split into a number of "partitions" or areas.  It might look something like:
+----+-+-------------+-------------+---------------------+
|BOOT|P|OTA Program 1|OTA Program 2| SPIFFS              |
+----+-+-------------+-------------+---------------------+

When you upload over UART you upload all that structure, and that structure can be changed.  When you upload over OTA you only upload one of "OTA Program 1" or "OTA Program 2". One of those is active and the other is inactive. You upload to the inactive one and then at the next reboot that becomes the active one. This allows the system to confirm that the program has been written correctly before running it to reduce the chances of bricking a device in the field.
Because of this you can never upload anything that doesn't fit into one of the OTA program partitions.
One risky option which you would have to do thorough local testing of first, is to write a program which, when executed, will change the partitioning. You would have to make sure that it runs in the lower OTA partition so that the inactive one is the one that gets both moved and expanded, which may take a little trial and error.
Once that has happened you should be able to upload a larger OTA program into the new, bigger, inactive OTA segment.
But that's only supposition and it's not something I have ever done or heard of anyone doing.


cannot resolve overloaded function... error

The function parseInt is a function and you have to add parameters with ( and ), even when it has no parameters, thus instead of

 numBlueBlink = Serial.parseInt;

you have to write

 numBlueBlink = Serial.parseInt();

See Serial.parseInt for a reference.


The problem is that wspeedIRQ() is a member function (i.e. it's part of the Teste class), but attachInterrupt() expects a non-member function (i.e. a function which is static and/or not part of a class at all).

This is a very important distinction in C++ because it affects how the compiler calls the function behind-the-scenes. There is unfortunately no way to use a member function directly with attachInterrupt().

Various workarounds are possible though. The simplest is to write a wrapper function which calls the member function. For example:

Teste teste;

// This is a non-member function...
void isr()
{
    // ...which calls the member function:
    teste.wspeedIRQ();
}

void setup()
{
    //...

    // Setup interrupt to use a non-member function
    attachInterrupt(0, isr, FALLING);
}

As a side note, your implementation of wspeedIRQ() won't compile at the moment anyway. The reason is that this. is invalid. It's a pointer so the correct syntax is this->.

(In practice, you usually don't need to use this to access member data. C++ figures it out automatically, unless there's a naming conflict.)


Pulling the enable pin on Adafruit PowerBoost to low (It's connected to VBatt!)

Your biggest problem is that the module defaults to on. There is a 340kΩ resistor pulling the EN pin up to VBAT all the time, so to turn it off you have to actively override that pullup.
Ideally you would modify the module by removing that resistor (R13) and adding your own resistor between the ENABLE and GND pins. You can the override that with both a button and a P-channel FET in parallel to turn the module on.
For example:

simulate this circuit – Schematic created using CircuitLab
Now normally R1 pulls ENABLE to ground turning the module off.  You press SW1 and it pulls ENABLE up to VBAT and turns it on.  5V then gets supplied to the Arduino, at which point you need to set the GPIO to output and pull it HIGH.
This causes the gate of M2 to be pulled above its threshold voltage (make sure it has a threshold voltage between 0V and 3V) and it starts to conduct pulling the gate of M1 below its threshold voltage (must be between 0V and -2V) bypassing switch SW1 keeping the system enabled.
You can now let go of SW1 and it will all stay powered on until you either set the GPIO LOW or set it to an INPUT.
Note that resetting the Arduino (for programming, for example) would cause the boost module to shut down and require re-powering with SW1 (or through the GPIO if you have the Arduino powered through USB for programming of course).
However if you don't want to or can't modify the module then things get a little nastier.
To make it default to OFF R1 in the above schematic will have to be low enough value that the voltage presented at the ENABLE pin is below 20% of the battery voltage.  R1 and the existing 340kΩ pullup resistor form a voltage divider, so you need to calculate the size of resistor that will allow it to be below 20% VBAT.
Since a voltage divider just gives you a proportion of the input voltage whose ratio is the ratio of the "top" resistance in the divider to the total resistance we don't care what the voltage is, only the ratio.  And we don't really care about the exact value, only that the result is below 20%.  So we can pick a good common value.
However we don't want a value that is too low, because the voltage divider will be draining power from the battery all the time, so the higher the resistances the less the power drain will be.
For example if we pick the common value 47kΩ we see that:
    R2           47000
 ------- = --------------- = 0.11 (11%)
 R1 + R2    340000 + 47000

Which is below the 0.2 (20%) that we want, which is good.  Calculating the current at a typical battery voltage of 3.7V we get
     V          3.7
I = --- = -------------- = 0.000010 (10µA)
     R    340000 + 47000

10µA is not much, on the scale of things, but it's good to know about it when you're working from a battery since it will form part of your power budget calculations.


What is the worst time case for Arduino Mega?

Yes.

(For better guidance than that, we'd need to know more.)