Disable other buttons while one of buttons is pressed I'm making a project with three buttons. What I'm trying to do is to disable other buttons (make them not respond to a click event) when one of three buttons is pressed.

For now I have this code:

    const int button1=3;
    const int button2=4;
    const int button3=5;

    int button1State=0;
    int button2State=0;
    int button3State=0;

    void setup() {
    pinMode(button1, INPUT);
    pinMode(button2, INPUT);
    pinMode(button3, INPUT);
    }

   void loop() {
   button1State=digitalRead(button1);
   button2State=digitalRead(button2);
   button3State=digitalRead(button3);

   if( button1State == HIGH){
   // do some stuff
   }

    if( button2State == HIGH){
    // do some stuff
    }

    if( button3State == HIGH){
    // do some stuff
    }

    }

Do you have any ideas how I could do it?

Thanks is advance for any suggestions!

The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.

Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.

I strongly recommend you use this task as a practice task for learning about finite state machines.

Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy_Switch.png for example. A state machine can also help you with this.

If you don't want to learn about FSMs, read on:

initialise last_button_pressed to 0 (meaning no button pressed)
if last_button_pressed>0
   if not(is_button_pressed(last_button_pressed) then
      last_button_pressed=0
else (no button is pressed)
   for each button_to_check (1,2,3)
      if last_button_pressed=0 and is_button_pressed(button_to_check) then
         last_button_pressed=button_to_check


ESP01 to DC Motor powered via Battery with Power Regulator Hi I'm wanting to control a dc motor through esp-01 and to have it powered by batteries. To keep my esp-01 safe, I have found the esp-01 adapter to regulate voltage. I am wondering if anyone could provide a simple schematic of the wiring? I'm wanting to keep the design small so no breadboard if possible.

It's not clear what you mean with "adapter to regulate voltage".

Typically, one would use some form of driver.

The TB6612FNG, for example, comes on PCB, both as standalone and with additional chip with I2C interface, like this one: https://wiki.wemos.cc/products:d1_mini_shields:motor_shield

It is very convenient if you need to use multiple motors, as you can have several configurabe I2C addresses, and each driver has 2 channels.


SoftPWM update limitations i'm using arduino to dimmer 9 led strips with different output pins after an FFT audio analysis gives results at 60Hz = 16ms. [FFT is performed by a PC and sent to arduino using a RF24 module]

I started the project using SoftPWM on pins D2->D9 & A4 with a lower frequency update but now i'm having problems increasing the frequency update. I have already wired 6 copies of that board and i'm looking for a software solution

To diagnose the problem i performed a test sending a pwm value and zero at a certain frequency, if the frequency is high you can only see a lower emitted power

If I set the pwm once I have a stable signal (led intensity)
If I set the pwm every ~10ms (10ms on @ certain pwm, 10ms at pwm=0) I have an unstable intensity, repeating the test on the pin 6 with a normal analogWrite i don't have the problem. With 10ms i clearly see it blinking at a random frequency (~20Hz=50ms), with 15ms I only see it random fluctuating

I'm using arduino Pro mini - 5V - 2kB
Without signals arduino performs 16k cycles/second (most without changing anything), with a 10ms signal it runs at 14k cycles/second so it seems not a load problem.

Can someone help me regarding this problem?

Should I change library
Should I move to a lower level to rewrite a more performing library
Should I use only 6 std pwm, draw again the board, print them again, weld all components again, and test it again?

Thanks!

PS: I can't create the SoftPWM tag for a reputation problem, can a moderator do that?

The problem is not a SoftPWM limitation but a physical one. SoftPWM have a PWM cycle at 60Hz, that makes impossible to update output faster than 34mS and that explain why I see low frequency trying to change the state with every 10 ms.

Hardcoding the IRS I can reach a much faster PWM cycle, keeping the same PWM frequency I have roughly 60% less of CPU used. With a full CPU load and latest version of the code I can reach ~600Hz PWM cycle. I decided to use a ~300PWM cycle to have enough CPU to perform other tasks (mainly handle RF24 to receive packets @ 60Hz and, if needed, forward them too other bases)

Even at higher frequencies average intensity is not stable, but higher the frequency more stable the result. That can be explained because the eye "average" incoming light and that average is not very stable

Since leds are used to produce visual effects I don't need a very accurate output, and 300Hz are enough. (I also don't have big mosfets and I don't want to stress them with higher frequencies)


Printing char array from array of structs in progmem to serial (I apologize if this is a c++ question, I'm too green to know if this is unique to the Arduino IDE)

I've moved an array of structs into my PROGMEM because I was running into memory issues:

#define HU_ADDR                 0x190
#define ALL_AUDIO_ADDR          0x1FF
#define MY_ADDR                 0x360
#define UNKNOWN_ADDR            0xFFF

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEONRARE,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC,
  ACT_PRESSAM,
  ACT_CD,
  ACT_STATIONFOUND,
  ACT_ENABLECD,
  ACT_CD2
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  word Payload[24];
  char Description[20];
};

const MessageDef MessageTable[] PROGMEM = {
  {ACT_POWERON,           HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x00, 0x100, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                    "Tune Knob"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,    {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                       "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,     {0x46, 0x01, 0x11},                                                                                "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,     {0x60, 0x45, 0x01, 0x11},                                                                             "Passive: Strong"},
  {ACT_PASSIVEONRARE,     HU_ADDR, UNKNOWN_ADDR, 4,     {0x100, 0x20, 0x01, 0x11},                                                                            "Passive: Fierce"},
  {ACT_PASSIVEON_0,       HU_ADDR, ALL_AUDIO_ADDR, 16,  {0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x100, 0x80, 0xF1, 0x31, 0x74},    "Vol Knob"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,    {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                                   "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x00, 0x9F, 0x31, 0x62},                                                                             "No DISC available"},
  {ACT_PRESSAM,           HU_ADDR, ALL_AUDIO_ADDR, 24,  {0x00, 0x60, 0x31, 0xF3, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x30, 0x00, 0x58, 0x00, 0x6C, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AM/FM Switch"},
  {ACT_CD,                HU_ADDR, ALL_AUDIO_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x01, 0x30, 0x01, 0xFF, 0xFF, 0xFF, 0x00},                                   "CD switch?"},
  {ACT_STATIONFOUND,      HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                     "FM station found"},
  {ACT_ENABLECD,          HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x77, 0x00, 0x81, 0x00, 0x00, 0xF1, 0x31, 0x60},                       "Enter CD mode"},
  {ACT_CD2,               HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x62, 0x45, 0x01, 0x11},                                                                             "CD message 2?"}
};

const byte MessageTableSize = sizeof(MessageTable)/sizeof(MessageDef);

I've adjusted accordingly in my code segments that reference this data using pgm_read_byte_near() for example. However, I'm not really sure how to get the Description field anymore. When MessageTable was in dynamic memory I could just use:

Serial.println(pgm_read_word(MessageTable[msgid].Description))

But now that seems to be printing... maybe the addresses of the data? Instead of printing out the character array I need to see. How do I parse this more correctly?

You can use the strncpy_P(char* dest, const char* src, size_t maxLen); function which will copy a zero-terminated string of at max maxLen bytes from PROGMEM into RAM. Then print the string from RAM.

Example code:

//We have global buffer in RAM. +1 for 0 termination
char descBuf[20 + 1];

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

    //Copy the description string of the first message in the buffer
    strncpy_P(descBuf, MessageTable[0].Description, 20);
    //Print it
    Serial.print("Description: ");
    Serial.println(descBuf);
}

Together with your code above, that prints on my Arduino Nano as:

Description: Tune Knob

If you don't want to have a 21 byte big buffer in RAM (or there are larger strings you wish to print), you can also use the pgm_read_byte function to read and print the string characters byte-wise. Example:

Serial.print("Description: ");
char c = 0;
for(size_t i=0; i < strlen_P(MessageTable[0].Description); i++) {
    c = pgm_read_byte(MessageTable[0].Description + i);
    Serial.print(c);
}
Serial.println();

For further reference, see the Arduino documentation on PROGMEM: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


Arduino Leonardo model differences I was thinking of buying another Arduino, and the Leonardo looks appropriate.

However I am confused! The Comparative Tables seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)

There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?

I assume I can use the Uno Prototyping shield on the Leonardo.

At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.

Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.

The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.

It's still the same chip, and still connected up in the same way.


Using TXD1/RXD1 on ATmega1280 for USB communication I have a few MakerBot Mightyboards running off ATmega1280 chips that can no longer use their standard USB port to connect to a computer (to make a long story short, there's a little inductor that blew up between the USB port and the 8u2 chip and it is essentially impossible to replace). I have noticed, however, that they have headers for the RXD1 (PD2) and TXD1 (PD3) pins on the 1280 as seen in this picture:

Would it be possible to hook up an external 8u2 (or similar) chip programmed as a USB to serial converter (something like this) and use it as if it were the normal USB port (e.g. for uploading firmware)?

(I wanted to add atmega1280 as a tag, but it doesn't seem to exist)

Not directly, no.

The USB interface connects to TX0 and RX0 - you have access to TX1 and RX1. The bootloader is set to look at TX0 and RX0.

You would have to compile and install a new version of the bootloader that is set to use TX1 and RX1.


IEEE 754 for integer Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.

I use this to convert float and works fine i have another code in javascript to revert it.
But when used it with integer values it just gives some values and the revert doesn't work as supposed to.

So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.

this is the code i use in arduino.

void IEEE754( float val, int pos)
{
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

also, does anyone has the revert code for arduino?..

IEEE 754 is the specification for floating point values. Integers aren't floating point values so this function of yours can have nothing to do with integers.

On an Arduino (8-bit):

A float value is 4 bytes in IEEE-754 format.
A long value is 4 bytes in little-endian format.
An int value is 2 bytes in little-endian format.
A byte is a byte.

To convert 4 bytes into a long you can use:

long val = (payload[3] << 24) | (payload[2] << 16) | (payload[1] << 8) | payload[0];

An int value is just the lower two bytes of the same kind of conversion:

int val = (payload[1] << 8) | payload[0];

You can use the same method (albeit backwards) to get the bytes to put in your payload:

long val = 12345678L
payload[0] = val & 0xFF;
payload[1] = (val >> 8) & 0xFF;
payload[2] = (val >> 16) & 0xFF;
payload[3] = (val >> 24) & 0xFF;

You can also use the same technique as your existing function with different datatypes, since all you care about is the byte content not the format or meaning of the bits within it:

void int2payload( int val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 2 ; i++) {
      payload[pos + i] = array[i];
  }
}

void long2payload( long val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}


Thermosensor Error - 'Wire' does not name type? Here is the code I am using:

#define D6T_ID 0x0A
#define D6T_CMD 0x4C

int ReadBuffer[35];
float ptat;
float tdata[16];

#include <Wire.h>
void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(500);

}

void loop() {

}
  int i;
  Wire.beginTransmission(D6T_ID);
  Wire.write(D6T_CMD);
  Wire.endTransmission();

  Wire.requestFrom(D6T_ID,35);

  for (i=0; i<35; ++i) {
    ReadBuffer[i] = Wire.read();
  }

  ptat = (ReadBuffer[0]+(ReadBuffer[1]*256))*0.1; //Reference Temp

  for (i=0; i<16; ++i) {
    tdata[i] = (ReadBuffer[(i*2+2)]+(ReadBuffer[(i*2+3)]*256))*0.1;
  }

  float tempF;

  if ( ((tdata[0]*9.0/5.0)+32.0)>0 )
  {
    for (i=0; i<16; ++i)
    {
      tempF = (tdata[i]*9.0/5.0)+32.0;
      Serial.print(tempF);
      Serial.print(',');
    }
    Serial.print((ptat*9.0/5.0)+32.0;
    Serial.print(',');
    Serial.println();
  }

    }
  }

This is the error I am getting:

exit status 1
'Wire' does not name a type

And it highlights this area of code:

Wire.requestFrom(D6T_ID,35);

I am completely new to using the arduino and coding so I am not sure if I already have the wire library that this code requires but when I look at the libraries in the Tools menu it is there. Do I need to download another library? If so can someone send me the link? Can someone explain what the error means? This is all foreign to me.

Thank you

You've goofed up your braces and none of that code is in loop(). Look at the braces in the code and make the appropriate corrections.


Does the MKR WIFI 1010 support the arduino mouse and keyboard controller? I am working on a project right now that needs to connect to my computer via bluetooth and access the arduino mouse and keyboard library. In my research, I've found that only the Leonardo, Due, and Micro can emulate cursor movements, but they need to have additional hardware like the HC05. I would like to keep the amount of hardware I use to a minimum, but I understand if there is no way around it. Is there any way to use the MKR WIFI 1010 like a Leonardo, or would I need to get one of the aforementioned boards and then get a bluetooth module hooked up?

PS this is my first dive into bluetooth, so any additional resources to aid me in my journey would be much appreciated.

Yes, the Arduino SAMD boards are supported by the Arduino Keyboard and Mouse library.

Nano 33 IoT is a smaler alternative to MKR 1010.

But the MKR1010 or the Nano33 IoT with original NINA firmware doesn't yet support classic Bluetooth like the HC-05 module. The ArduinoBLE library and the NINA firmware support only BLE which is different.

But there is a simple way to replace the NINA firmware with the ESP32 Arduino basic Bluetooth sketch SerialToSerialBT and then use it from the SAMD. This way the NINA module will be degraded to something like a HC-05.


Create own apache web server on Arduino Uno... just like you can on a raspberry pi? I was wondering if I could create my own apache web server on my Arduino Uno, just like I did on my raspberry pi - https://www.raspberrypi.org/documentation/remote-access/web-server/apache.md

Anyone have any idea about this? From my research it seems like I cant achieve the same results on an arduino uno.

Thanks

You can only make a very, very, very basic webserver, that won't be able to handle more than a few requests per second.

You also need to add something like an ethernet shield, and probably an SD card reader. Which would make it about the same price as a Pi.

It's possible, but very limited, not practical in most cases, and not that much cheaper.


Reading atomic radio clock i have some data logging to do. And i want some what accurate time meaning accuracy has to be +/- 1 minute.

I have considered a RTC, but then i thought. When i was 10 i got a watch that kept time from this radio clock. And if it is possible 20 years ago to make a clock that updates automatically in such as small form factor, then i should be able to do it with my arduino today.

Does anyone know of a guide/solution with components where i can read this atomic radio clock?

So, the first consideration goes to the radio propagation aspect. Every country does things a little different with their radio clocks. And you might only have good signal a few times a day. For a nice overview, check out a solution for the German DCF77. If you're totally set on using a radio clock, time-nuts has discussed in the past ripping open a $10ish clock to get at the fun parts of a WWVB receiver, so that's one overview of the pool you're diving into.

For myself I've skipped past the terrestrial time keeping and went straight to GPS. Find a receiver that provides a pulse-per-second and attach that to an interrupt and process it alongside the timestamp; you can see how I've gone about that in both code and final product.

I think GPS is both easier and more precise than the alternatives, assuming you're above ground and can pick up satellites. I think of RTCs as something to tell me the day and the year, while GPS can tell me the second. But you could consider ripping the antenna out of a cheap bedside radio-controlled clock and using that to set an RTC, careful to consider whether you want a cheap RTC (DS1307) that drifts a minute per day or a slightly more expensive RTC (DS3231 or ISL1220) that drifts a minute per month. (Rough numbers of course.)


Is my Arduino possibly broken? We work in groups on a project at school. We had to build an electric scheme with an Arduino to make a small car moving.

We got the parts from our school, except the Arduino (we had to buy it ourselves). We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers.

The car worked for a while, but then we wanted to change the program and tried to upload new software to the Arduino. Now the Arduino is not recognized by any computer.

We tried several things, like multiple times unplugging the USB cable, hitting the reset button on a specific timed moment (some method found on the internet).

But it still doesn't work. When the Arduino is connected via USB, the 'on' LED on the Arduino is on. After that all we came also to the conclusion that some people made mistakes on building the electric scheme...

Is it possible that the Arduino is broken, since the battery has 11.5 V?
If the Arduino isn't broken, can the problem that it's not recognized by the computer be solved?

(Arduino Uno)

Considering that you used resistors to lower the 11.5V to an cough - cough "very normal and regulated 5V", that most certainly is the problem.

The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.

The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.

The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.

Need anymore help, just comment. I'll be happy to help you!


Negative voltage output Or Controling negative voltage I've got an RGB led strip I'm trying to control. It's a 12v, 4 pin strip.
Pin layout seems rather odd to me as 1 pin takes 12v of power and 3 pins (that go to ground) control the colors. In other words, the LED colors are controlled by limiting outgoing voltage.

White- +12v
Green- Green in negative voltage
Red - Red in negative voltage
Blue - Blue in negative voltage

I've already made a similar setup that uses n-channel MOSFETS (or at least I think that's what they are) between the colored cables and the ground and Arduino power the MOSFET gates as necessary.

So my question is: is it possible to hook these LEDs up directly to arduino and control the negative voltage without aditional electronics?

As a slightly off topic question: Is there a specific name for elements that are controlled with negative voltages.

By the way, I'm using Arduino nano, although I don't think it is relevant at this point and I've got Mega and Uno aswell if needed.

No, it's not possible, since the voltages and currents involved (12V) are too high.  It will damage your board.

Your arrangement with N-channel MOSFETs is the correct arrangement.

By the way, you are not working with "negative" voltages at all - it's all positive - you just happen to be between the "load" and ground.

This is called a Low Side Switch since it is on the "low" (i.e., between the load and ground) side of the circuit.

The LEDs you have are in an arrangement called Common Anode in that the anodes (+ pins) of the LEDs are all tied together (common) and you control the cathode (- pins) of the LEDs.  It means you can use cheap N-channel MOSFETs that are (as you have seen) easy to control with a microcontroller.  The other arrangement, Common Cathode, where all the cathodes (- pins) are tied together and you switch the power to the anodes (+ pins) requires P-channel MOSFETs and N-channel MOSFETs to switch the P-channel MOSFETs, which increases costs.


Serial Module Echoing a `0x00` I am having a problem with a MAXIM Serial module (Config A) with a simple repeating code from COM port. When sending a character (k:0x6b) I receive a (0x00) echo.

Without the module and just connecting the arduinos crossing the TX/RX cables, I do not have any echo.

The echo persists, disregarding of:

The speed (from 38400 to 2000000 bps),
Using or not the high speed options (2.3MOhm for 250000bps) of the MAXIM,
Using or not 120 ohm terminal resistors,
Both grounds are 0V, connecting them has no effect,
Removing the A (red) B (green) Serial Bus Cables (???). Message not send in this case, as expected (!).

What could be the problem?

Devices:

Two Arduino Mega 2560,
Two MAX3292, one for each arduino,
AWG24 Cable, shorter than 7 in each.

Config A: With Module (00 echo), Half Duplex (f.19 p.13).

Config B: Without Module (No echo), only crossed cables

Code:

long rate=38400;
void setup() {
    Serial.begin(rate); while (!Serial);
    Serial1.begin(rate); while (!Serial1);
    pinMode(22,OUTPUT);
    pinMode(23,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(22,1);
        digitalWrite(23,1);
        s=Serial.read();
        Serial1.write(s);
        Serial1.flush();
        digitalWrite(23,0);
        digitalWrite(22,0);
    }
    if (Serial1.available()){
        s=Serial1.read();
        Serial.write(s);
    }
}

Execution: Four k sent, 0x00 echoes received. After this, four k send from other arduino, received successfully.

Epilogue.

Actually, the problem was a resistor at the RO output, not shown in the diagram ("The problem is in the code you didn't post").

It was a voltage divider for a 5V3.3 conversion in the Arduino Due case, useless in the Arduino Mega, but still there.

Theorizing a reason, that resistor caused a spike at the output (?), thus forcing the module to interpret it as another byte, an empty one (?).

After removing the resistors, it worked perfectly.
Now I migrated this back into Arduino Due, but with a diode plus a pull up resistor as a 5V3.3 converter.

Check your wiring! My guess is the twisted pair (A-B swap).

I've checked your code, it seems right. Please note that /RE and DE were designed that way so you can simply connect them and control with only one pin.

I don't have the exact same hardware, I had MAX485 and Arduino Nano at hand. Nano only has one hardware serial, so I've used the SoftwareSerial library instead.
I've connected them, adjusted your code to my setup, and it worked. Here it is in case it helps to troubleshoot your issue. I've also optimized your version a little bit (but it worked before so the bug is somewhere else).

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX

const int dir_pin=9;
const int dir_transmit=1;
const int dir_receive=0;
long rate=38400;

void setup() {
    Serial.begin(rate); while (!Serial);
    mySerial.begin(rate); while (!mySerial);
    pinMode(dir_pin,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(dir_pin,dir_transmit);
        while(Serial.available())
        {
          s=Serial.read();
          mySerial.write(s);
        }
        mySerial.flush();
        digitalWrite(dir_pin,dir_receive);
    }
    while (mySerial.available()){
        s=mySerial.read();
        Serial.write(s);
    }
}


Upload sketch via Bluetooth using HC-06 module I'm dealing with an application in which I need to upload sketches remotely to an arduino UNO board. I successufully managed to upload sketches using an HC-06 bluetooth adapter. The only problem is that I am forced to manually press the reset button once the bluetooth link is established. Is there a way to automatically reset the arduino, in a software or hardware way,  so that it will be able to accept and install the incoming and sketch?
Would it be enough to activate a digital pin connected to the reset at the right timing prior the upload process starts?

Use a BJT/FET.

For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.

Just bring the digital pin HIGH to reset your arduino.


How do I remotely acquire data from Arduino based portable device? I am making a device which will have an Arduino board and a sensor attached to it. The sensor will acquire data every 10 minutes and the data will be uploaded to my server. The size of every upload is about 200 characters. I'd like this device to work anywhere in my city (US).

What are my options for uploading data to my server? Keep in mind that it will work without human intervention. FYI... this is NOT for reconnaissance device! ;)

I can't guarantee anywhere in your city, but this hack will work pretty much wherever there is cell coverage for the carrier you choose.

You'll want the GSM shield.

Picture from Arduino

Anyway, it uses pins 2, 3, and 7 on it. It also has the ability to solder (on the bottom of it) a microphone and speaker connection. You'll need to buy a SIM card and a contract to connect your shield to a network. I don't know how often you would use this, but I've seen a pay-as-you-go plan that charges you $2 for unlimited talk/text/internet per day. If you're going to use this once a month, that would be the way to go. I didn't look to see if they supported the GSM shield (it was on TMobile's site). You would want to contact them for more details. Also, depending on where you live, I don't know if you would get good coverage. This goes with any cell phone provider, but make sure that you get coverage where you want to go (and don't always trust the maps they provide).


What are these stray resistors on the Arduino Mega schematic? I am using the Arduino Mega schematic found here and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

Does anyone know what these are and where they go?

Those are unused resistors in resistor arrays.  The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

Elements A and D of Resistor Network 1 (RN1)
Elements B and C of Resistor Network 2 (RN2)
Element C of Resistor Network 3 (RN3)


Power source for arduino project The project is to make a 4WD car using arduino uno(clone) and four toy dc motors. I am using a adafruit motor shield v1.2(clone). The car is required to run autonomously, please suggest batteries for the arduino and the shield.
Also when I am using external power connector for arduino, all the motors start at different timing.

I've been using usb power packs.

Easy to source (can be found in all electronics stores and many general stores).
Come in many sizes (500mAh to 20,000 mAh are common).
Rechargable, usually by using a generic phone changer with a usb micro connector.
Not costly.
Quite roubust.
Most Arduino boards and many motor driver boards are designed to be powered from usb.

Make sure you get one that is rated for enough current for your project.


NodeMCU ESP8266 disconnected from WiFi after several hours running I tried to test NodeMCU ESP8266 with this code from here

                #include <ESP8266WiFi.h>
                #include <WiFiClient.h>
                #include <ESP8266WebServer.h>
                #include <ESP8266HTTPClient.h>

                /* Set these to your desired credentials. */
                const char *ssid = "dummy";  //ENTER YOUR WIFI SETTINGS
                const char *password = "12345678";

                //Web/Server address to read/write from
                const char *host = "192.168.43.128";   //https://circuits4you.com website or IP address of server

                //=======================================================================
                //                    Power on setup
                //=======================================================================

                void setup() {
                  delay(1000);
                  Serial.begin(115200);
                  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
                  delay(1000);
                  WiFi.setSleepMode(WIFI_NONE_SLEEP);
                  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot

                  WiFi.begin(ssid, password);     //Connect to your WiFi router
                  Serial.println("");

                  Serial.print("Connecting");
                  // Wait for connection
                  while (WiFi.status() != WL_CONNECTED) {
                    delay(500);
                    Serial.print(".");
                  }

                  //If connection successful show IP address in serial monitor
                  Serial.println("");
                  Serial.print("Connected to ");
                  Serial.println(ssid);
                  Serial.print("IP address: ");
                  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
                }

                //=======================================================================
                //                    Main Program Loop
                //=======================================================================
                void loop() {
                  HTTPClient http;    //Declare object of class HTTPClient

                  String ADCData, station, postData;
                  int adcvalue=analogRead(A0);  //Read Analog value of LDR
                  ADCData = String(adcvalue);   //String to interger conversion
                  station = "A";

                  //Post Data
                  postData = "status=" + ADCData + "&station=" + station ;

                  http.begin("http://192.168.43.128/c4yforum/postdemo.php");              //Specify request destination
                  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header

                  int httpCode = http.POST(postData);   //Send the request
                  String payload = http.getString();    //Get the response payload

                  Serial.println(httpCode);   //Print HTTP return code
                  Serial.println(payload);    //Print request response payload

                  http.end();  //Close connection

                  delay(5000);  //Post Data at every 5 seconds
                }

It was running well and posted data to Database after a few hours. Then It was disconnected from WiFi somehow . Of course I reset power supply again It's connected.

How should I do to fix with that code to reconnect WiFi right after that accident Or any other Solution  for that ? Thank you

What you need to do is leave the board connected to your computer and watch the serial monitor to capture the output during the crash.  If the board has a true crash it will output a bunch of information which may tell you why you it is crashing.  It could be a strings/heap problem or maybe a memory issue since you are declaring a new http object every 5 seconds.  Maybe try putting the HTTPClient http; line up where you declare the host variable so that it is a global variable and not a local variable.

Since your loop doesn't test to make sure the wifi connection is still good then if you get a disconnection then the program will just fail and never try to re-connect.  So at the start of your main loop put the same wifi testing logic that is also in the setup function. If the connection is down then reset and start from the very beginning to re-establish the wifi connection.

if (WiFi.status() != WL_CONNECTED) {
    ESP.reset()
  }


Sound localization using two mics, Arduino Uno on MATLAB I have been trying to achieve this for a long time using the ITD method and have gone through various articles on the net.
I want to know if its possible to actually achieve sound localization using an Arduino Uno and two MEMS mics with a high gain (https://www.sparkfun.com/products/9868).
I have been trying this on MATLAB using the a=arduino() command and readVoltage command but the main issue I face is that for a particular sound (clapping for instance) the time difference between the two mics is not always the same which results in different direction predictions.
We managed to increase the low resolution of the Arduino by removing unnecessary operations. Now we are able to get an array of size 750 for 10 secs giving a resolution of 0.01 secs. I am not sure if that is enough.
I basically have 3 arrays, one storing the sampling times, and the other two storing the amplitudes of the two analog inputs at that particular time in the first array.
Now I look for a peak in one and then the corresponding near peak in the second one and then compute the time difference. After this I can compute the angle using the speed of sound and the distance between the mics.
Please let me know how I can make this work or where I am going wrong.

Let's assume a microphone distance of 0.5m (which may be just small enough for you). Sound travels with about 300m/s in normal conditions. Let's also say, that you want at least a precision in the angle measurement of 15°.

As stated in the project Mikael linked, it is important that the distance to the sound source is big enough (so that the waves can be seen as planar). Then you have the following situation:

We are interested in the difference in distance, that the waves have to travel to the two microphones. It can be calculated by delta s = d * sin(alpha). With 15° we get delta s = 0.13m. The time difference is calculated by delta t = delta s/v, where v is the speed of sound. We get delta t = 0.43ms which equates to 2.32kHz sampling frequency. Since we use two microphones that must be sampled sequentially, the sampling frequency must be doubled. In the end we have a sampling frequency of 4.64kHz. So your sampling time of 0.01s wouldn't be enough for that.

The largest time difference in this setup (with the sound source in line with the microphones) would be 1.6ms, so your sampling time would be too big even for this.

Regarding the transmission with a baudrate of say 115200 baud this shouldn't be a problem.

But the actual speed of your setup highly depends on your code, which you haven't shown. Maybe this forum post can help you going further.


Arduino Controlling through C# i would like to measure some signals from arduino and send it to a pc using USART and display the results in a c# winform application. Does anyone have such a project example ?
Besides, i want to send the data in live time mode, each values should be directly transmitted and then the second measurement ( sample rate 100 kHz )
Thanks a lot

Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino?
Yes the board is connected by USB, but that's only so it can open a serial connection.
To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.


Arduino LCD shows only black boxes I've hooked up my Arduino on this LCD, and after running the following code, all I see is a row with black boxes and another one empty.

//LiquidCrystal d(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(0, 1, 2, 3, 4, 5);

void setup() {
     lcd.begin(16, 2);
     lcd.print("hello, world!");
}

void loop() {
     lcd.print("hello, world!");
}

Wiring:

(The UTP cable is used just for the data lines :-)

Actual wiring photos: (sorry for the total klutz in the wiring, I had limited solid-core wires so I had to use these scrap ones)

The problem was that the R/W pin on the LCD was left floating, after I connected it to GND, I started working :)


How to pass a changing value to a graphic display using Arduino? I am using an EA DOGM132-5 graphic display, they also have provided a library for Arduino, so everything is nice and easy. The library has a function for easily passing a string to the LCD.

void dog_7565R::string(byte column, byte page, const byte *font_adress, const char *str)
{
unsigned int pos_array;                                         //Postion of character data in memory array
byte x, y, column_cnt, width_max;                               //temporary column and page adress, couloumn_cnt tand width_max are used to stay inside display area
byte start_code, last_code, width, page_height, bytes_p_char;   //font information, needed for calculation
const char *string;

start_code   = pgm_read_byte(&font_adress[2]);  //get first defined character
last_code    = pgm_read_byte(&font_adress[3]);  //get last defined character
width        = pgm_read_byte(&font_adress[4]);  //width in pixel of one char
page_height  = pgm_read_byte(&font_adress[6]);  //page count per char
bytes_p_char = pgm_read_byte(&font_adress[7]);  //bytes per char

if(type != DOGM132 && page_height + page > 8) //stay inside display area
        page_height = 8 - page;
  else  if(type == DOGM132 && page_height + page > 4)
    page_height = 4 - page;

//The string is displayed character after character. If the font has more then one page,
//the top page is printed first, then the next page and so on
for(y = 0; y < page_height; y++)
{
    position(column, page+y); //set startpositon and page
    column_cnt = column; //store column for display last column check
    string = str;             //temporary pointer to the beginning of the string to print
    digitalWrite(p_a0, HIGH);
    digitalWrite(p_cs, LOW);
    while(*string != 0)
    {
        if((byte)*string < start_code || (byte)*string > last_code) //make sure data is valid
            string++;
        else
        {
            //calculate positon of ascii character in font array
            //bytes for header + (ascii - startcode) * bytes per char)
            pos_array = 8 + (unsigned int)(*string++ - start_code) * bytes_p_char;
            pos_array += y*width; //get the dot pattern for the part of the char to print

    if(type != DOGM132 && column_cnt + width > 128) //stay inside display area
                width_max = 128-column_cnt;
    else if(type == DOGM132 && column_cnt + width > 132)
       width_max = 132-column_cnt;
            else
                width_max = width;

            for(x=0; x < width_max; x++) //print the whole string
            {
                spi_out(pgm_read_byte(&font_adress[pos_array+x]));
                //spi_out(pgm_read_byte(&font_adress[pos_array+x])); //double width font (bold)
            }
        }
    }
    digitalWrite(p_cs, HIGH);
}
}

So I just use the function in the sketch with the variables I want and I can easily show a string, but I want to show a changing value for example a temperature reading Tc.

int ThermistorPin = 0;
int Vo;
float R1 = 10000;
float logR2, R2, T, Tc, Tf;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;

Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
Tc = T - 273.15;

But the string function doesn't support variables. Can someone help me to adjust the string function to take variables or perhaps suggest a better way altogether?

You have to first convert the floating point value to a string, then pass the resulting string to the dog_7565R::string() function.

It looks like the standard sprintf() provided by Arduino does not support the %f format for floats, so you may have to find another way to convert it or write your own conversion function.


How to eliminate noise from PWM controlled 12V fan at low speed I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino.

When putting HIGH on the port the fan works perfectly at high speed, but when I want to lower the speed (say analogWrite(fanPin, 150)) it starts to make a humming noise. I believe this is caused by the use of PWM.

What is the best way to control the speed of the fan without (too much) noise?

ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.

Update: Here is the schema I am using:

I had the same problem with a 5V fan.  Something simple worked for me: To decrease the PWM frequency.  You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions.  Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency.  In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds.  And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.


Compilation Error - Yellow LED blinking as I have installed & connected Arduino UNO board to Windows XP PC This is the first time when I have installed Arduino IDE (arduino-1.8.10-windows.exe) in my Win. XP SP-3 OS and it seems that the Arduino IDE software installation is successful without any hitch.

After restarting the PC, connected it  with Arduino Uno board through USB-Printer cable provided with the board and then selected Arduino Uno, Selected Port: COM3 (Arduino/Genuino Uno) - as I have verified in the Device Manager that the Arduino Uno installed in COM3 port.

As soon as I have connected Arduino Uno board to my PC, the yellow LED started blinking slowly. As I have tried uploading the sketch -  File>Examples> 01.Basics>Blink - there is an Error message that says, "Error compiling for board Arduino Uno" - even though the yellow LED still kept blinking without a reasonable act from my side.

So, where have I gone wrong - either in performance or in understanding? And is there any suggestion for making things right?

I thank you.

// the setup function runs once when you press reset or power the board
void setup(){

  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);

}

// the loop function runs over and over again forever
void loop(){

  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);

  // wait for a second
  delay(1000);

  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);

  // wait for a second
  delay(1000);

}

The yellow LED may be flashing because there may be a "Blink" LED program pre-installed on the Arduino.

To diagnose the "Error compiling for board Arduino Uno", we need to see the sketch you are trying to upload, and detailed error messages. If you go to Arduino > Preferences, check the "compilation" and "upload" checkboxes beside Show verbose output during:. Display line numbers is another checkbox you could enable.


Problem with 2 decimal places/2 significant figures Lora/GPS Shield + Arduino Uno + PLX-DAQ (latest custom version)

I have a problem on how to generate more than 1/2 decimal output.
Currently, I'm trying to generate GPS Lat and Long(code from TinyGPS++) on PLX-DAQ

Just like in the image. Latitude generated in 1/2 decimal places.
I'm trying to get more than 2 decimal places.

For example : from 3.2 to 3.123953

Coding link:
https://www.dropbox.com/s/rqjpnsc9pg33f9n/Coding.txt?dl=0

Thanks.

You're talking about the output from this line?

Serial.println( (String) "DATA,DATE,TIME," +flat+ "");

drop the use of the String class and make that two separate print statements.  Then you can use the second argument to print to define the precision.

Serial.print("DATA,DATE,TIME,");
Serial.println(flat, 6);

That gets the same end result output going out the serial line, but lets you specify the precision and avoids the nasty String class.


Module that can both detect Voltage (12V) and Control current I need a module for ARDUINO that can both detect Voltage (12V) and Control current between 2 pins (12V), like a relay on another device
I have found relay modules to control pins and another module for 4-channel Voltage detection, but it seems like a lot of components and wiring.
Is there any module that can do both?

You don't need another module to detect voltage on an Arduino.  The UNO, which I assume you are using, has 6 analog inputs (A0-A5) that can directly read voltage.  The only problem is that you want to measure a voltage up to 12V and the Arduino can only handle 5V.  So the solution is to DIVIDE that using two resistors in a voltage-divider configuration so that you only see 5V at the Arduino when there is 12V on the signal.
From here: https://www.electroniclinic.com/what-is-a-voltage-divider-or-potential-divider-formula-and-practical-uses/
you can see how to make one:

As far as controlling a "current" that is usually done with a relay.  There are no on-board relays but there are the digital outputs that can drive a small relay or can be connected via some other circuitry like a couple of transistors to drive just about any size relay.


Accessing digital pins from the Atmega 16u2 on the Uno I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick).
Is it possible to access the digital pins of the UNO from the ATmega16U2?

No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.


I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture? For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

Arduino Uno
Hx711 amplifier module
1 kg load cell
2 push buttons
A 4 digit 7-segment display module we found online, but we don't know its specific name
HC-05 Bluetooth module, no specific manufacturer
Lilypad switch CR2032 battery module
DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.

I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.

What can I do next?

You can find the parts on fritzing.org. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an Arduino Pro Mini with 3.3V and HC-05 without a breakout for 5V Arduinos.

Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.


How to loop over analog pins? I want to do something along the lines of

for (int i = 0; i < 4; i++) {
  analogRead(i);
}

Which appears to work, but the following does not:

for (int i = 0; i < 4; i++) {
  pinMode(i, INPUT);
  pinMode(i + 4, OUTPUT); // should make Analog Pin (i + 4) into an output
  digitalWrite(i + 4, LOW);
  analogRead(i);
}

Instead, it appears to treat the pin addressed by digitalWrite(i + 4, LOW); as one of the digital pins.

Do I really have to explicitly specify A0, A1, A2, ... anytime I want to loop over the analog pins?

Yes, the analog pins must be addressed using A0, A1,... when using them for digital I/O.

Depending on the board you are using A0,A1,etc. are mapped to different values (for instance it looks like A0 is 18 on some boards but 14 on others.

One solution for looping over the analog pins would be this:

static const uint8_t analog_pins[] = {A0,A1,A2,A3,A4};
// Setup pins for input
for (int i = 0; i < 5; i++) { //or i <= 4
  digitalRead(analog_pins[i]);
}

If you are using the analog pins only with the analogRead() call you can use 0,1,... instead of A0,A1,...


Arduino with ESP8266 I have completed the circuit and code to interface ESP8266 module with Arduino UNO.

When i send AT,AT+RST from serial monitor the reply is correct .

But when i send AT commands to search WIFI networks (AT+CWLAP) & connect to WIFI (AT+CWJAP="SSID","password") the reply is ERROR.

But the IP address (may be default) is obtained as 192.168.4.1
 when i send AT+CIFSR .

Here is my code

#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3

void setup()
{
    Serial.begin(9600);
    esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
    if(esp8266.available()) // check if the esp is sending a message
    {
        while(esp8266.available())
        {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            Serial.write(c);
        }
    }
    if(Serial.available())
    {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);
        String command="";
        while(Serial.available()) // read the command character by character
        {
            // read one character
            command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
    }
}

Finally i found the solution .

Send AT+CWMODE=1 first , then all other commands working fine.


DC motor makes noise but does not rotate i am following Jeremy blum's tutorial on youtube. link i have done the exact same circuit design as he has.

but the dc motor just makes a continuous beep sound when i run this code.

int motorPin = 9;

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

void loop()

{
    for(int i = 0; i <= 255; i++)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);

    for(int i = 255; i >= 0; i--)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);
}

I am clueless as to why this is happening. would be glad if someone could help me out here.

For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.


How to tell what components are compatible with Arduino Due? I am interested in using the Arduino Due in an upcoming project, however I am worried that the other shields/components that I need will not be compatible with it, because, according to that link:

  The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0 Arduino pinout.

The components I need to use are:

NightShade Electronics energyShield
Solar Panel
Servo Motors

Essentially a solar panel will power the energyShield (rechargeable battery), which in turn will power multiple servo motors.

I cannot tell if the energyShield uses the 1.0 pinout or not. I am also worried that since the the solar power generates 6V it will overload the energyShield which is rated at 3.3V. At the same time, I am worried that the servo motors, which seem to require 4.8V, will not be capable of being powered by the energyShield which outputs 3.3V. Thoughts?

Bonus Points if someone can explain to me what the "1.0 Pinout" is, and whether it is the latest/most modern pinout available for Arduinos.

As far as I understood this energyShiled accepts any input between 5-24V and output 5 - 3.3V. This specs are compatible with arduino Due. And with the solar panel.

You can always power servos from seperate source or from the same battery but with seperate direct line.


Multiplication, division. What is wrong? const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

Arduino UNO printed in monitor console:

C1 = 30000   (ok)
C2 = 143164  (must be = 10)
V1 = 143164  (must be = 10)
V2 = 0       (must be = 10)
V3 = 0       (must be = 10)

What is wrong?

300

and

1000

are integers.

What

long V2 = (300 * 1000)/30000;

really does is take the integers 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.


How can I stop my servo looping when my sensor doesn't detect movement? I have this project with my Arduino UNO where I want my servo motor SG90 to go full speed to 180 degrees when the PIR sensor sends HIGH value and go slowly back to zero when the value is LOW.
I have this code working where the servo goes full speed back to zero:
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);
  //time for calibration

  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    myservo.write(0);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion ended!");
}

I'd like the servo to go slowly back to zero, so I tried this :
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);

  //time for calibration
  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees 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!");
}

The problem is with this code the servo does go slowly back to zero but then goes full speed back to 180 and again and again ....
Any idea? I'm a beginner in Arduino, so I assume it must not be that hard to figure out.
Thanks.

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);
}


esp8266 esp-01 crashing, restarting over and over I flashed my ESP-01 with the nodemcu firmware 512k version, and everything was working fine.  I testing some lua scripting on init.lua and it was working.  Then, after writing a bunch of code and uploading, the module restarted.  And it restarted.  And it's still restarting, over and over again, and prints to serial

CÀbc0°ýbcü¨HøNodeMcu 0.9.4 build 20141230  powered by Lua 5.1.4
ö,3bþÈH

It was always printing the garbage in there before, so I'm not worried about that.  However, I can't send anything to the device--I can't send serial commands, or reflash the device.  I'm thinking I overloaded the memory or something.  Anyone have any ideas for recovering this brick?

Turns out I was pulling up on the GPIO0 pin, instead of down.  Ensure you have the correct pin-out when flashing.

ESP-01 VCC - 3.3v Serial Adapter
ESP-01 GND - Ground or Minus Serial Adapter
ESP-01 RX - Connect to TX on Serial Adapter
ESP-01 TX - Connect to RX on Serial Adapter
ESP-01 CH_PD - 3.3v Serial Adapter
ESP-01 GPIO0 - Pull low by connecting to ground / minus

There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over.  That is also what was happening.  There is some problem with wifi.sta.getap() that exacerbates this.


How to keep the regulator cool while battery powering the arduino and accessories? I'm trying to build a battery operated hand lantern. It has the Arduino, an MPU6050 accelerometer, and 4 APA106 (WS2812B-like) LEDs.

If everything's powered through the Arduino's 5V pins, that's 80mA for the Arduino, 240mA for the 4 LEDs, and let's round up to 5 mA for the MPU6050.

If I'm using 5x AA batteries for 7.5V (at full charge) that should be 2.5V * 325mA of power wasted or just under a watt that'll be heating up the regulator? I'm not sure if that's huge or tiny or in between or what.
What's the most sane way to power this device for an absolute newbie?

1W is near the limit of what a small LDO can handle. It will get considerably hot.

I would use 4 batteries instead of 5, and a 3.3V Arduino clone instead of the UNO, and power the LEDs directly from the batteries. You could also use your original UNO, feeding it with 6V on a 5V pin through a simple diode, which would drop it to something like 5.4..5.3V.


Power Arduino and LED strip I saw this question about powering Arduino and LED strip. So, I searched for a 5v 4a power supply and foud this one.
How does that adapter provide power for both Arduino and LED strip? I thought I might need DC barrel Plug to alligator clips but I'm not sure as this is the first time I use an external power supply to power multiple components.
So what do I need to make that wall adapter able to power both Arduino and LED strip?

I assume, that your problem is how to connect everything to the power supply.
You have some different options, depending on your requirements. The linked adaptor (barrel plug to alligator clips) doesn't seem to fit the barrel plug of the power supply. So you cannot use that. Especially it seems, that both are the male part of the connection. For every plug connection you need a male and a female part of the same connector type (much like your power outlet on the wall is a female part, while the power plug on your supply is a male part; in terms of plug systems).

The best way (especially, when you want to not only experiment, but also use it as a fixed product) would be to solder the wires. For this you need a soldering iron, soldering tin and something to clean the iron (sponge for soldering irons for example).

You can buy a barrel jack, solder wires to it and connect them to the Arduinos 5V pin, ground and to the LED strips power lines in parallel (from + pin of the supply one wire each to 5V Arduino and + pin of the LED strip, from - pin of the supply one wire each to ground of Arduino and - pin of the LED strip). Then you can still disconnect the power supply from your project.
If you don't want to buy a barrel jack and you don't need to disconnect the power supply from your project, you can splice up the cable of the power supply (only the LOW VOLTAGE PART!!!). You can use nail scissors, if you don't have other tools for it. Cut off the plug by cutting the cable a few cm before it. Then cut the plastic between the 2 connected parts of the cable for a few cm, so that you get the 2 individual cables (+ and -).  Use the scissors to carefully cut the outer plastic around the cables and remove about 1cm of it, so that you now have 2 cable ends with the bare cable core free. Twist each end, so that it each little copper strand stays in the cable shape. Then solder the cable ends. Now you can take another wire/cable to solder the connections from the two ends to the described parts. Be sure to isolate the connections at the cable (in the best case with shrinking pipes, otherwise you can also use tape).

If you don't want to solder, you can search for fitting connectors for every part. There are breadboard power adaptors, which should work with this power supply. They have pins on them, that you can not only use with breadboards, but you can also connect jumper wires to them. There also exist such adaptors for typical LED stripes, though that depends on the type of strip, that you have. When looking for jumper wires, you should make sure, that they are capable of conducting enough current. The Arduino does not need much current, thus standard jumper wires will be sufficient. But the LEDs can draw much more current, so that the standard jumper wires will start to smolder and catch on fire. Then you need some with a bigger wire diameter.

You can also use alligator clips, but in my experience, they only work for rather specific cases. The connection, that they make, is fragile and can be easily disturbed. They are slipping and rotating easily. When connecting the LED strip, you might easily connect + and - together and destroy the power supply. Also it is almost impossible with most of them to connect to a standard 0.1 inch pin (which are used on the Uno and Nano), without also connecting other pins. Unless you break out these pins with something else (like jumper cables), that is not a good choice.

You can now choose yourself, which way to go. If you plan to do more with Arduino and electronics, I would suggest, that you buy a soldering iron and the needed supplies. You will need it and they only cost a few bucks, if you just buy a simple one (back then I got one for 15€/$, which also had a temperature control, so you can also get it cheaper). If you don't want to buy it, but still want to solder, you could look for a maker space near your location.
I would go for soldering here, because you are very much limiting yourself, when you choose to do not. Then you need to buy fitting parts, which is more difficult.

how do I know what the ground is and the 5v?

For the power supply you can see it on the label. There you will find the following sign:

It means, that the outer shell of the connector is ground (-) and the inner pin is 5V (+). With cables there are 2 possibilities:

Often the wires inside a cable each have an own isolating plastic shell around them, which is color coded. Black is normally ground, while red is 5V/+.

When having a 2 wire cable, the cable is often designed as coaxial cable (which reduces noise on the signal). In that case you have one inner wire, which has it's own isolating plastic shell, and the outer wire, which is laid around the inner wire without any further isolation. The outer wire is normally ground.

When using an extra cable for connecting 2 parts, make sure to use the same wires on both sides (for example the red wire for 5V on both sides).
To be sure, you can check the voltage on the wires with a multimeter (also a very useful tool), when the cable is connected. A multimeter has a positive and a negative lead, which are marked as red and black respectively. When you connect the multimeter to the wires and it shows a positive voltage, you have found the correct association of the wires with their voltage (5V or ground).


How do software interfaces compare to hardware interfaces in therms of speed and reliability? The Arduino core includes numerous software interfaces mimicking the hardware interfaces provided by the chip and even extending beyond. My question is, if in a project I can either use software or hardware protocol, what would be the difference in stability, speed and versatility? Is there a reason why hardware interfaces are preferred? Because anyways the protocol is handled by the CPU or am I mistaking something?

In your question you ask about all communication interfaces in general, so the answer will be as general as your question.

Hardware interfaces should always be preferred to software interfaces, though there are situations, where it is a better or needed to use a software interface due to limited resources.

  Because anyways the protocol is handled by the CPU

That is mostly wrong. The communication protocol is done by the hardware in most cases, if you use hardware interfaces. Serial (UART) for example automatically sends out the byte, that is placed in the hardware buffer, with the set configuration. It does not rely on any software for that. The same goes for SPI or I2C. The protocol of the interface is handled via hardware.

Though at least for Arduino Core/library users there is more to it, that get's handled automatically. Since the interface hardware is limited, the software have to take care of the resulting or needed data. For example: All the interfaces mentioned above use a 1 byte buffer for the data. The software must read or write this data, so that the hardware can work. If you don't read the byte of data, that was received by the Serial interface, it might get overwritten by the next byte. The hardware cannot provide a buffer, that is generally big enough, since the manufacturer cannot know, how long the transmissions will be. So the interfaces get a 1 byte buffer and the software has to do the rest. For this reason all the libraries use a bigger buffer in their software, that gets filled, when the hardware sends a corresponding interrupt.

So: Hardware interfaces implement the basic interface protocol (how the bits get transmitted) in hardware, thus the software only has to provide and read the byte data. The stability, speed and versatility is only determined by how the manufacturer build the hardware of that interface. This limit is clearly specified in the datasheet and does not change with the code.

For software interfaces, everything is done in software. This also involves monitoring and setting the corresponding pins with the correct timing. In the best case the software can utilize general hardware functions like a pin interrupt, but if it cannot do this, it has to constantly monitor (poll) the pins to receive something. Software interfaces are often called "bit banged", because the software manually pushes out each individual bit with the exact needed timing. That is a tedious task, which often blocks the execution of other code, since the timing often is critical. Especially the timing introduces limits, since doing things in software often involves many clock cycles more, than it could be done by dedicated hardware (consider all the code to poll a pin and the multiple if statements to react to specific situations). For example: When you write data with SoftwareSerial the call to the write function will block, because is manually pushes out bit after bit. Or with SPI: With hardware SPI you can go to incredible clock speeds in the MHz range. You won't every get near that with software, because the software simply cannot run this fast.

Note, that depending on the actual hardware of the used chip, a library may need to implement parts of the protocol in software. For example this is the case for using I2C on an ATtiny85, which does not have full I2C hardware support. Instead the USI (Universal Serial Interface) can be used to implement some functions of the protocol in hardware and the rest in software.

TL;DR

Hardware interfaces lift the heavy duty of handling the low level protocol (transmitting the bits by the needed standard) (which can be rather complex) from the software
The Software then only handles the byte data, not it's transmission
Translating complex protocols from dedicated hardware to software (bit banging the data through simple pins) imposes great limits on speed and reliability.


Detect where pressure is being applied by using force resistors I have 3 force resistors in a row, on top of which I have placed a board. I read values from the resistors through analogue ports. My goal is to be able to detect whether someone is pressing on the top, middle, or bottom of the board.

So far I can easily detect the left and right, like this: I first calibrate the 3 sensors for 2 seconds. Then I detect if pressure is applied on any of the calibrated sensors. If yes, I sum for all of them the values that they return on each round of the loop, until force has stopped being applied. I finally compare the 3 values against each other and I find which received higher pressure in total. This works perfectly fine for the left and right. However, when the board is pressed in the middle, pressure is applied on all 3, since the board is flat. Sorting the values does not help, because very often the left and right sensors have recorded a higher value than the middle.

I noticed that when the board is pressed on the left, the right sensor records very few values, and the same for the other way around. So, I get a high success rate in detecting middle presses like this:

int threshold = 80;
if (left_sum > threshold && middle_sum > 80 && right_sum >80)
    return middle_pressed;

However, when someone presses hard enough on the left or right, the if statement is satisfied.

Is there a more accurate way to detect where force is being applied?

(Following is a quick schematic I made - I am not at all an expert so please excuse me for my mistakes, I just hope it illustrates more or less what it is supposed to)

simulate this circuit – Schematic created using CircuitLab

Please ignore the double arrows right on top of the resistors.

Let's assume that you have only two FSR sensors. With those you can make three virtual buttons (above the left sensor, above the right sensor and in the middle).

To measure someone's weight, it is allowed to have a scale under each foot and add both weights. We can use that to calculate the total force pressing to the board, by just adding the two forces.

The FSR sensors have a curve to calculate the force in newtons. It is very inaccurate, but works more or less. That can be added later. For now let's assume that it is linear to the ADC value of the Arduino.

Are the FSR sensors connected to an analog input and GND ? Do you have a resistor between the analog input and 5V ? I assume you do. You need the resistors so that a nice pressing force to the board results somewhere in the middle of the ADC range.

Pseudo code:

setup()

  Measure both ADC values (or a number of values and use the average)
  Store them as offsets in a global variable.

loop()

  Measure both ADC values, substract the offset.

  Translate the ADC values into force.
  The more force the higher the number should get.
  Any range is okay for now.
  They can be translated into Newton later.

  The total force is by adding the two forces.

  The position in percentage is the force of the right sensor
  divided by total force times 100.
  Then the position will be 0 for left sensor, 50 for middle
  and 100 for right sensor.

  If the total force is above threshold, then check the position.

  for example position -50 to 20 for left virtual button.
  for example position 30 to 70 for middle virtual button.
  for example positition 80 to 150 for right virtual button.

You can start by printing the forces to the serial monitor. Press the board and check if the numbers increase when pressing more.

Don't get confused when you print the position. It will be very noisy when no force to the board is applied. It should be valid when the total force is above the threshold.

For the position I allow a large error of 50 percent left of the left sensor and right of the right sensor. It depends on the mechanical construction and the rest of the code if that makes sense.

Print the results to the serial monitor.
If that is working well, then you have to detect a single press.

Let's assume that as soon as the threshold is reached, a press to a virtual button is accepted. Let's not wait until the peak of the force is reached.
The State Change Detection example can be used to create a single event for pressing the virtual button.

Any jitter or noise (for example a single press to the board results into two events for the virtual button) can be solved by averaging or filtering in software. I think that it will be needed.

I'm not sure if all of this is okay. I hope that someone else will look into it as well.


error loading an array of strings I'm trying to have a user enter a series of strings. This is my code.

this is my error message - cannot convert 'String' to 'char*' in assignment

char* titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup() {
 Serial.begin(9600);
 Serial.println("Storing numbers in an array");
}

void loop()

{

for (int x =0; x < 5; x++)
{
  if (Serial.available() > 0)

  {
   Serial.println("Enter a word... ");
   titles[x] = Serial.readString();

    Serial.println(" ");
    Serial.println(chartitles[x]);

   }
  }
 }

So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:

String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup(){
  Serial.begin(9600);
  Serial.println("Storing numbers in an array");
}

void loop(){
  for (int x = 0; x < 5; x++){
    if (Serial.available() > 0){
      Serial.println("Enter a word... ");
      titles[x] = Serial.readString();
      Serial.println(" ");
      Serial.println(titles[x]);
    }
  }
}

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:

String titles[]

Instead of:

char* titles[]

The second change is related to Serial.println(chartitles[x]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.


Set SPI MOSI pin to idle low on a Due? I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?

Here's a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

I have managed to set MOSI to low by setting bit 26 in PIOA->PIO_PER, PIOA->PIO_OER and  PIOA->PIO_CODR registers. To use SPI again, bit 26 in PIOA->PIO_PDR has to be set (this cancels the effect of PIOA->PIO_PER).


Understanding Arduino input and outputs I am a research scholar working on exploring the diffusion kinetics of metallic ions into substrate materials. To do so, I have to process 486 specimen combinations and it has been very difficult and practically impossible manually. Therefore I am attempting to automate my PG research using Arduino UNO.
To automate my reactor I estimate there would be 7 limit switches of lever type, 1 temperature sensor (K Type thermocouple), and 1 push button switch for start and stop. For the output, there would be 2 solenoids and 2 relays for stepper motors, and one relay for the alarm speaker. I would also like to log the temperature against time. Kindly suggest the feasibility of the automation using Arduino UNO. Kindly suggest other means for doing the same.
Thanks.

Yeah, you can totally make that work with an Arduino Uno. You would have 14 digital pins, as well as 6 analog pins that can also be used as digital pins.


Why is this code not working? So I am trying to use Port Manipulation to turn on LEDS but I need to use PORT Manipulations for specific reasons.

//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
PORTA =  B0000000; //29--->22
PORTC =  B0000000; //37--->30
PORTD =  B0000000; //45--->38
}

void loop(){
 PORTA =  B1000100;
 PORTC =  B0101000;
 PORTD =  B0000010;
 delay(1000);

 PORTA =  B1010000;
 PORTC =  B0001010;
 PORTD =  B0100000;
 delay(1000);

 PORTA =  B0010100;
 PORTC =  B0100010;
 PORTD =  B0001000;
 delay(1000);

}```
Heres the code for Arduino Mega 2560

You need to set the ports to output first, before you can use them.

To do that you use the DDRx (Data Direction) registers.  Your code should look like:

//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
    // Set the pins all to output
    DDRA = 0xFF;
    DDRC = 0xFF;
    DDRD = 0xFF;

    PORTA =  B0000000; //29--->22
    PORTC =  B0000000; //37--->30
    PORTD =  B0000000; //45--->38
}

void loop(){
    PORTA =  B1000100;
    PORTC =  B0101000;
    PORTD =  B0000010;
    delay(1000);

    PORTA =  B1010000;
    PORTC =  B0001010;
    PORTD =  B0100000;
    delay(1000);

    PORTA =  B0010100;
    PORTC =  B0100010;
    PORTD =  B0001000;
    delay(1000);
}

You can read more about direct port manipulation here.


How is it possible to access the CPU registers using memory addresses? The following is taken from ATmega328-328P Data sheet.

According to this, I can access all the 32 registers in CPU using memory addresses. For example:

 unsigned char *register = 0x0;

will access the first register. Is this true? if so, then is this also possible to do on regular CPUs (like my laptop), since I thought you can only use a pointer to access memory and not CPU registers.

Is the register mapped into the SRAM in this case?

Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.

As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

  Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM


5V and Vin pins on Arduino I am working on connecting two Arduino boards (Arduino Uno & Arduino Nano). I am trying to run a stepper motor  connected to Arduino Nano with two digital Pins on Arduino Uno to alter the direction of the stepper motor(BYJ48) connected to the arduino Nano.
While making connections I attached the pins as:

1] 5V  (UNO) -> 5V (NANO) & GND (UNO) -> GND (NANO)

2] 5V (UNO)  -> 5in (NANO) & GND (UNO) -> GND (NANO)

Both [1] & [2] worked fine initially but I kept the arduino powered and tried toggling the Vin with 5v. Nothing went wrong in the beginning but later fumes started coming out and I dont know the reason why?
Was that because I kept the power on while toggling between Vin & 5v ?
NOTE: besides the code and success in running the possible reason of fumes is much important here.

You can try software serial communication between the two boards. Any two digital pins of one board can be used as Rx and Tx, and make sure the roles of Rx and Tx are reversed on the other board. See the Software Serial library:
https://www.arduino.cc/en/Reference/SoftwareSerial


Why do I get negative voltages for a PWM waveform? I used my Arduino Uno's pin 3 to generate a PWM output. The code is:

void setup() {
  // Put your setup code here, to run once:
}

void loop() {
  analogWrite(3, 180);
}

I connected the output directly with a oscilloscope.
And the output waveform is shown below:

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease.
Why does it behave in such a way?

At first you had the scope AC (Alternating Current) coupled.  Then you switched it to DC (Direct Current) coupled.

AC coupling is used to remove the DC component of a signal.  It places a large capacitor between the probe and the internal amplifier.  This is used, for instance, if you want to see a small signal with a large DC offset.  But it can also attenuate and / or alter signals that are low in frequency.

When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs.  As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes.  Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.

DC coupling is where there is no coupling capacitor between the probe and the internal amplifier.  Everything comes through.  For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.


Can I use the PWM pins as regular digital input/output pins? In regards to the arduino which has pwm pins, can I use these pins as normal input/output digital pins or not? Thanks in advance.

Yes you can use them as ordinary digital io pins. PWM is essentially a normal digital output pin that is repeatedly turned on and off at a high rate.

The magic is that the turning off and on is done in the hardware according to the duty cycle  (I.e. there is no need for software to perform the on/off operations) . This is why only some pins can do h/w PWM, because the PWM hardware is not added on to all pins.

If you are not using the pin for PWM, it is available for you to use as required.


Using MMA8451 accelerometer to count steps I'm trying to use an Adafruit MMA8451 accelerometer to create a pedometer-type device that counts steps. I'd like to initiate a counter that says "if the x-axis readout is > some threshold, add 1 to the counter" so that once the counter reaches a certain point, I'll be able to trigger a separate event (like an LED turning on). I'm an Arduino beginner, and would appreciate any pointers in the right direction as I work through this.

I'm using the Sparkfun Redboard and the Adafruit MMA8451, and wrote a loop to check whether the x-axis readout was over 5. If it's over 5, I want it to add 1 to the accumulator. However, it's accumulating 1 each readout regardless of what the 'x' reading actually is. Can anyone tell what I'm doing wrong? A nudge in the right direction would be much appreciated.

Code is here:

/**************************************************************************/
int lastStepCount = 0;
int accum = 0;

#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

Adafruit_MMA8451 mma = Adafruit_MMA8451();

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

  Serial.println("Adafruit MMA8451 test!");

  if (! mma.begin()) {
    Serial.println("Couldnt start");
    while (1);
  }
  Serial.println("MMA8451 found!");

  mma.setRange(MMA8451_RANGE_2_G);

  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");

}

void loop() {
  // Read the 'raw' data in 14-bit counts
  mma.read();
  Serial.print("X:\t"); Serial.print(mma.x);
  Serial.print("\tY:\t"); Serial.print(mma.y);
  Serial.print("\tZ:\t"); Serial.print(mma.z);
  Serial.println();

  /* Get a new sensor event */
  sensors_event_t event;
  mma.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print("X: \t"); Serial.print(event.acceleration.x); Serial.print("\t");
  Serial.print("Y: \t"); Serial.print(event.acceleration.y); Serial.print("\t");
  Serial.print("Z: \t"); Serial.print(event.acceleration.z); Serial.print("\t");
  Serial.println("m/s^2 ");

  /* initiate for loop to count movement— this is the piece I'm having trouble with */
  if (event.acceleration.x >= 5);
    accum = accum + 1;
  Serial.print("X Counter: "); Serial.print(accum);

  /* Get the orientation of the sensor */
  uint8_t o = mma.getOrientation();

  switch (o) {
    case MMA8451_PL_PUF:
      Serial.println("Portrait Up Front");
      break;
    case MMA8451_PL_PUB:
      Serial.println("Portrait Up Back");
      break;
    case MMA8451_PL_PDF:
      Serial.println("Portrait Down Front");
      break;
    case MMA8451_PL_PDB:
      Serial.println("Portrait Down Back");
      break;
    case MMA8451_PL_LRF:
      Serial.println("Landscape Right Front");
      break;
    case MMA8451_PL_LRB:
      Serial.println("Landscape Right Back");
      break;
    case MMA8451_PL_LLF:
      Serial.println("Landscape Left Front");
      break;
    case MMA8451_PL_LLB:
      Serial.println("Landscape Left Back");
      break;
  }
  Serial.println();
  delay(500);

}

**Update: the output I'm getting is as follows. The "X Counter" accumulates even when the x-reading is well below 5...not sure what's going on:

X:  1Adafruit MMA8451 test!
MMA8451 found!
Range = 2G
X:  144 Y:  50  Z:  4052
X:  0.34    Y:  0.11    Z:  9.66    m/s^2
X Counter: 1Portrait Up Front

X:  138 Y:  62  Z:  4052
X:  0.34    Y:  0.11    Z:  9.70    m/s^2
X Counter: 2Portrait Up Front

X:  0   Y:  48  Z:  4040
X:  -0.02   Y:  0.11    Z:  9.67    m/s^2
X Counter: 3Portrait Up Front

X:  -780    Y:  106 Z:  3814
X:  -1.80   Y:  0.25    Z:  9.11    m/s^2
X Counter: 4Portrait Up Front

X:  -510    Y:  106 Z:  4008
X:  -1.46   Y:  0.20    Z:  9.68    m/s^2

Change your if statement - remove ; (semicolon) from the end.

Use this:

if (event.acceleration.x >= 5)
accum = accum + 1;

Notice there is no semicolon after if statement


7 segment LEDs on wood face I'm not sure this is right place for this question, but does anyone have any idea how a 7 segment display is projected or embedded in wood for products like this?

Full product info at http://www.amazon.com/Cube-Wood-LED-Alarm-Clock/dp/B00D6DI0LE

Another example:

From: http://www.selectism.com/2013/11/27/a-wooden-led-alarm-clock-and-wireless-bluetooth-speaker-from-gogroove/

This is done by carefully placing a layer of wood veneer over the 7-segment displays. The veneer is thin enough to let the light pass through. I wouldn't be surprised if some manufacturers use brighter than normal LEDs to make the display easier to see. Here is a video detailing an example.

It is also possible to simply drill out the wood to make it very thin where the 7-segment displays go. Here is an example of drilling the solid wood to be very thin.


Problem with motor driver shield I have recently bought a L293D shield and 2 BO motors. Whenever I connect the motors to the shield it makes a beeping noise. I searched online and found that I need to change PWM frequency but I know nothing about it and anyone please tell me about the PWM frequency and how to change it.

I have used almost every sketch found online but condition remains same. I am using 9V battery as External power supply and it is absolutely new. Please help me.

Acting as a conduit for Google: Arduino Change PWM Frequency shows me:

https://playground.arduino.cc/Code/PwmFrequency

Which has the following example function:

/**
 * Divides a given PWM pin frequency by a divisor.
 *
 * The resulting frequency is equal to the base frequency divided by
 * the given divisor:
 *   - Base frequencies:
 *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
 *      o The base frequency for pins 5 and 6 is 62500 Hz.
 *   - Divisors:
 *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
 *        256, and 1024.
 *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
 *        128, 256, and 1024.
 *
 * PWM frequencies are tied together in pairs of pins. If one in a
 * pair is changed, the other is also changed to match:
 *   - Pins 5 and 6 are paired on timer0
 *   - Pins 9 and 10 are paired on timer1
 *   - Pins 3 and 11 are paired on timer2
 *
 * Note that this function will have side effects on anything else
 * that uses timers:
 *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
 *     millis() functions to stop working. Other timing-related
 *     functions may also be affected.
 *   - Changes on pins 9 or 10 will cause the Servo library to function
 *     incorrectly.
 *
 * Thanks to macegr of the Arduino forums for his documentation of the
 * PWM frequency divisors. His post can be viewed at:
 *   http://forum.arduino.cc/index.php?topic=16612#msg121031
 */
void setPwmFrequency(int pin, int divisor) {
  byte mode;
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 64: mode = 0x03; break;
      case 256: mode = 0x04; break;
      case 1024: mode = 0x05; break;
      default: return;
    }
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | mode;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | mode;
    }
  } else if(pin == 3 || pin == 11) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 32: mode = 0x03; break;
      case 64: mode = 0x04; break;
      case 128: mode = 0x05; break;
      case 256: mode = 0x06; break;
      case 1024: mode = 0x07; break;
      default: return;
    }
    TCCR2B = TCCR2B & 0b11111000 | mode;
  }
}

And numerous results from this SE community also:

https://www.google.com/search?q=arduino+change+PWM+frequency+site:arduino.stackexchange.com

Which note methods for calculating/setting specific frequencies and pitfalls and side-effects of making such changes.


How do I extract code from an arduino? I updated and uploaded some code on another computer that got wiped and didn't send the new code to my current computer, the updated code is still on the board but I don't have access to it. How do I get it back?

The short answer: You don't.
With enough know-how, you could probably extract the executable binary from the Arduino, but the source code is not installed on the device. You would need to run a decompiler on the binary. (Or read the machine code directly.) The output of a decompiler is usually pretty ugly however, and will look quite different from the original source-code. It won't have meaningful variable names, class names, or function names, and the code structure will likely be a little different than the original source code.
EDIT:
As mckenzm pointed out in his answer, you could download the binary image from your Arduino, and then copy it onto another Arduino, but all that would let you do is to make an exact copy of the program. You wouldn't be able to modify it at all.