Send text according to an ultrasonic measurement, on battery I have this big bucket where I would like to install an arduino on the top of the bucket where it would calculate the % of the bucket being filled up with water. Then, every day at night the arduino will send a text message (via SIM card) to the server where it would collect data for that bucket.

As far as a beginner point of view, I can understand that I will need:

an Arduino Board
PING))) Ultrasonic Distance Sensor
Battery pack that would allow to run the board for a year?
and the Arduino GSM Shield (integrated antenna) OR the GSM/GPRS Module M10?

My question is:
What arduino board do I need for my setup?
How long will 2 large or 4 AA batteries lasts for receiving a value from the ultrasonic sensor once a day and sending that value to a server? The point of the instrument is to be as small as possible.

First of all: what is the intention of your setup? What are you trying to measure, what do you want to do with the data? Where is the bucket located, in your backyard or miles away in a forest?

I foresee some problems with your current setup.

First of all, you need a enclosure that keeps your 'duino and other components dry and at a comfortable temperature. I don't know how severe the weather conditions are, but stuff can get unreliable when used close to the min/max operating temperatures. Can you find an enclosure that can protect your electronics against the elements?

My advice: think of a good enclosure.

Second, do you really think PING))) is the best sensor? Have you already tested how it behaves around water? Are the measurements correct?
Another option would be an array of metal strips, one connected to +V or GND, the others to separate ports on your Arduino. Space them evenly from the bottom of your bucket to your maximum water level (drill a hole in the bucket to prevent overflowing or drowning your duino). Poll the pins at a predefined interval (not too short, keeping battery life in mind) to see which ones make contact with the water (allowing current to flow from/to the pins from/to +V/GND)

My advice: do some research on sensors, or try to make your own

The best way to communicate with your 'server' (what are you going to use?) totally depends on how far it is from the bucket. GSM shields are quite pricey, other alternatives may be preferable (and do not have additional phone costs).
Is your server on the other site of the window? Bluetooth? Somewhere in your backyard? Zigbee. Across the street? High-power Zigbee (if allowed by local authorities). Far away but with WIFI access? Zigbee, posting data to an online place. In the middle of nowhere but with great cell phone reception? GSM.

My advice: check out wireless communication possibilities. There's a ton of them, each with pros and cons.

Last hurdle, energy. Your battery setup will most definitely NOT be able to provide enough energy for a whole year. There's just too little juice in them.

Arduino and standalone AVRs often have a sleep mode, in which power consumption can be very very low. Google is your friend on this one. Still, that won't let your setup last a year.

Unless there was a gigantic glowing ball of plasma hanging around some 8 lightminutes from here and we could harness its incredible power with the use of photovoltaic elements... Wait, we totally can! Using (a) solar panel(s) and some simple circuitry you can recharge your batteries, and depending on the weather conditions this could keep your project up and running for a year.

My advice: get down and dirty with small solar panels.

I really appreciate your ambition. If done right, this could be quite the project for a beginner! Just make sure you thoroughly research every part of the system, on itself and as a whole. This could prevent a lot of disappointment and unnecessary costs, while only expanding your knowledge.

Good luck!


D1 Mini; is there a fuse? While this board (listed on ebay as D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.

I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.

So something has burned between the 5V on the usb and the 5V on the regulator.
I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.

Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?

Or could the short between 5V and GND have caused a track to burn?

Try measuring with a voltmeter to compare the good board to the bad one. If it is the diode as mentioned in the comments under the question, you should get a different reading on the bad board. It should be fairly easy to replace if you have a soldering iron and a steady hand.


I2C_anything from Nick Gammon. Value of two senders to be received and printed by receiverslave Following the suggestion of Fiendish to post here:
Hello
Nick, thank you very much for this I2C-anything library that works a treat with two arduinos (one sender, one receiver).
Is there any suggested method or at least an example sketch of having two different sender arduinos send their floats to the receiver  e.g. by alternating slave adresses in the receiver loop? With a simple re-insertion of the section (but with a different address) into the receiver sketch restarting with Wire.begin() and then Wire.begin(new address) things are botched up.
In addition: if I define -float f in sender A- and -float e in sender B- the receiver keeps on printing the float e value in the serial.Print ("float value e"); serial.println(e); -postion, no matter if I swap from Sender A to sender B -by changing the SCL/SDA connections,  and the serial.Print ("float value f");serial.println(f); prints fancy numbers.
If at least the swapping would cause the floats to be printed in the correct position I could maybe switch the respecive senders I2C down in turns....
Of course hotplugging /hotswitching SDA and SCL from senders causes the senders sketch to be blocked at times.
The idea of sending data from Sender B to Sender A, and from Sender A to to receiver left me frustrated the last few hours, due to the fact that Im a total noob and/or that its simply not possible to have two masters send to one slavereciver without running into i2C conflicts. Unless some unknown acrobatics is performed.
The ultimate idea is to have two separate megas (with i2c sensors attached to them) execute feedbackloops and still be able to transfer these values and other values to a display via I2C. the alternate way could be that a dac is used to translate the I2C values into voltages that hardware....)
Any help greatly appreciated
Best
Daniel

Dear Chrisl and Sim Son
Please accept my apologies for not replying earlier, am still recovering form a timbering accident and have limited painless access to my laptop.
thinking in boxes: BOX 1 = Arduino Mega number one regulates the pressure of proportional valves (via I2C conected quaddac MCP4728 to 0-10V) based on the flowvalues of 4 I2C-connected FLowsensors.
BOX 2= Arduino Mega number two does the same with a second set of 4 flowsensors and 4 analog proportional valves.
Splitting this to two arduinos was originally because a) i was unable figure out how to get 2 DACS on the same I2C line and handle the LDAC address fiddling which turned out to be a good approach because the total number of required GPIO pins exceeds the available number of pins of one Mega (many rotary encoders attached, TTL signal delayer for 8 channels, pots to set values, status LEDS.
Both arduinos are supposed to send the values for the flow-setpoints, actual pressure values, actual flow values, other sensor data to a third arduino MEGA =BOX 3 that displays all kind of things on a large TFT. (for what its worth, this third Mega has some inputs from a different set of other I2C sensors that basically provide TTL signal outputs, if event-criteria have been met. the latter TTL are fed back to the first two arduinos to provide decision criteria in if loops)
So, i learn from you that the multimaster approach unlikely to be fun at all, especially given my limited knowledge and loathing /ignorance to handle and send strings. You will at least laugh at me now but i saved quite some time the on day i wrote to you by simply translating all the flow etc values of BOX 1, Box 2-Ardinos (pressures, flowsetpoints and actual flow values into voltages with the help of additional multiplexed DACs, then I pick up the the voltages with I2C-ADCs hooked to the Arduino with the SPI-display (BOX 3) that in turns translates into the true values and prints to the TFT. Any delay and inprecision at the displays side is acceptable so far, analog value fluctuation has been smoothed, the additional hardware is no issue at this stage of the project.
I am sorry that his original issue regarding I2C led me astray to oldfashioned analog data processing
BUT: if you have any hints or pointers to libraries as how two arduinos that act already as I2C Masters can send their data (a bundle of floats) via UART/RXTX, or any other bus to a receiver that handles these as printable variables: more than welcome, i will try to keep abreast of what you suggest.
Best
Daniel


Make an Xbox 360 controller with an Arduino Uno I was thinking of making a custom Xbox 360 controller (racing wheel) with the Arduino Uno plugged into the Xbox. How would I emulate the buttons/triggers on the original controller with the Arduino? Is there a library that can help me do this?

Arduino Uno's do not have a native USB Connection. However, if you use an Arduino Leonardo or Pro Micro, you can use MHeironimus's Joystick library, However I am not sure if they are specifically compatible with the XBox.

https://github.com/MHeironimus/ArduinoJoystickLibrary


Running code through functions I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

Here is the code i need to reproduce in a working format

void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

EDIT due to misunderstanding the question.

If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your runfor() function to accept a pointer-to-a-function parameter.

typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

ORIGINAL ANSWER

Your starting pseudo-code is nearly there.

void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

Changes I made:

change int to uint32_t to accommodate all possible values of millis().
change for keyword to while, which is the correct keyword for the loop type you want.
added semicolon after your timer assignment, per C syntax.


SIM800l is not Avalible I am using :
-arduino uno r3
-SIM800L

connection:

Arduino   SIM800L
5v     -->  vcc
gnd    -->  gnd
pin10  --> TX
pin11  --> RX

the led on the module blinks once each 3~5 seconds
but when i use the function sim.available() i got 0;
thus as i guess there is a problem .

the code :

#include <SoftwareSerial.h>
SoftwareSerial sim(10, 11);
int _timeout;
String _buffer;
String number = "000000000000"; //-> change with your number
void setup() {
  delay(7000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Sistem Started...");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  Serial.print(Serial.available());
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}

i looked the internet they say the voltage should be 3.7~4.2 itriedgivving 3.55 and it didn't work

Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.
For short test you can connect module directly to LiPo 3,7V.
You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

The power IC and the bypass capacitor should be placed to the module
as close as possible.

SimCom, SIM800_Hardware Design_V1.09, available 27.11.2020


Reading two sensors at different frequencies... multiple Timer3? Originally, I had a single sensor which I was reading at 100MHz. I used Timer3 and function attached to it to do both reading and writing of the sensor data (print to com port).

Now I have added another sensor which can only be read at half the frequency. I still want to be able to write data in the same format as before for both sensor data at 100Hz, with slower sensor data just being repeated twice.

How do I handle this? Do I use multiple Timer3 attachments at different frequencies? I am planning to have three interrupts.. 1st for reading sensor A, 2nd for reading sensor B, and 3rd for writing data.

The rule is:

One Timer, One Interrupt.

When the timer overflows it triggers its interrupt. It only has one. That interrupt then runs your ISR.

If you are using a library to provide abstraction from the timer registers then it is down to that library how it calls your ISR. It is possible for one to provide a mechanism whereby you can "attach" multiple routines to the same interrupt, but that is quite a lot of work and overhead for a simple timer library to provide, so it is highly unlikely anyone would ever bother.

So how do you do multiple sensor measurements from one timer? Simple: just do multiple sensor measurements. You don't have to restrict yourself to just reading one sensor within your interrupt - you can read as many as you like. There is just a couple of caveats though:

The whole ISR must take less that 10ms to run or it will overrun the timer overflow period.
You cannot do serial from inside an interrupt*

So in your interrupt you read the sensors and add their values to a buffer. Then in your main loop you read that buffer to send the data out through serial. You may want to set a flag in your interrupt routine to alert the main loop that there is data available, or implement a circular buffer which has an equivalent of a .available() function to see if there is any data to read from it.

*You can place data in the serial TX buffer but it will not be transmitted out of the TX buffer until after the interrupt routine has finished. If you put too much data in that TX buffer it will block indefinitely waiting for it to empty.


Get hour with ctime (time library with ESP8266) #include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now = time(nullptr);
  Serial.println(ctime(&now));
  delay(1000);
}

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything.
Is it possible to do that?

The easiest way is to use the standard function localtime() or gmtime() and the struct tm.

void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}


HTTP POST from Arduino/ESP8266/ESP32 How to send parameters (x-www-form-urlencoded) EDIT: Thank you for the answer, also we had figured out how to do it Micropython too - I believe that it is relevant for the Arduino/ESP8266/ESP32 community to share this too.

https://github.com/46elks/46elks-getting-started/blob/master/code-examples/MicroPython/https_post_with_micropython.py

How should I include parameters from, to and message to http.post?

Is this the correct way to do it?
http.POST("'from:+XXXXX','to:+XXXXX','message:Hej'");

#include <M5StickC.h>
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#define USE_SERIAL Serial

WiFiMulti wifiMulti;

void setup() {

    USE_SERIAL.begin(115200);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    wifiMulti.addAP("YYYY", "ZZZZZ");

}

void loop() {
    // wait for WiFi connection
    if((wifiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        USE_SERIAL.print("[HTTP] begin...\n");
        // configure traged server and url

          http.begin("https://api.46elks.com/a1/sms");
          http.addHeader("Content-Type", "application/x-www-form-urlencoded");
          http.setAuthorization("XXXXX", "YYYYYY");
          int httpCode = http.POST("'from:+XXXXX','to:+XXXXX','message:Hej'");

        USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
         httpCode = http.GET();

        // httpCode will be negative on error
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                String payload = http.getString();
                USE_SERIAL.println(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(10000);
}

What format of message does the server expect? As you send "x-www-form-urlencoded" it should probably look like:

 "from=+XXXXX&to=+XXXXX&message=Hej"

where the different parts are

 "param1=paramValue1&param2=paramValue2&param3=paramValue3"

 param .... Name of the expected parameter
 = .... divides the param pair
 paramValue .... Content/value of the parameter
 & .... links the param pairs

so in your case

 int httpCode = http.POST("from=+XXXXX&to=+XXXXX&message=Hej");


ESP-8266 stopped working due to possibly faulty perfboard layout I have been following this tutorial to set up my ESP8266. I have also recreated on a perfboard the circuit provided in the tutorial, and I intend to use this perfboard circuit in my project.

The problem arises when I plug my ESP into the perfboard and try to talk to it through the serial monitor. When using a baud rate of 115200, the ESP responds to commands but in a garbled format. Also, the blue LED stays on after powerup for increasingly long periods of time. Now the blue LED is always on and the ESP no longer responds to any commands, except when reset and asked for the startup firmware info. I suspect that the ESP is now broken but am not sure how to check.

Also note that the ESP was working fine on a breadboard at 9600 baud, prior to the blue LED incident. Now it won't work with the breadboard either.

All commands were sent with newline and carriage return.

Is the ESP8266 broken? Could there be something wrong with my perfboard circuit? The circuit is rather dense and contains wiring for several other components in addition to the ESP-8266.

It turns out the real culprit was the AT+IPR=9600 command bricking the board. The board was "fixed" by obtaining the firmware and flashing it to the board using esptool.py. Download the repo's source code, navigate to the directory bin/at/, and see the file README.md to see which addresses to flash the different parts to.


Arduino UNO - Fluctuation of inputs and outputs I have some pots (100K) on my Arduino board. When I raise the value of one those resistance other pots are being changed (Not too much but it's significant). I have no idea what's going on. I tried to use a capacitor at the beginning of the circuit but didn't work.

These fluctuations change the value of my sensors too. When I raise the value of something other quantities change.

I'm powering up my Arduino using a USB cable.

Any ideas?

You seem to be experiencing cross-talk between the analog channels. This
happens because all the channels are funneled by an analog multiplexer
into the same sample-and-hold capacitor. If the source resistance is too
high, then the capacitor does not have enough time to charge to
the voltage of every channel.

Here is what the datasheet of the ATmega328P says about the
issue:

  The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less. [...] The user is recommended to
  only use low impedance sources with slowly varying signals, since this
  minimizes the required charge transfer to the S/H capacitor.

The problem can be mitigated by reducing the source impedance using a
capacitor at every pot wiper, or by giving more time to the
sample-and-hold circuit: make many dummy readings before the one reading
you want to keep. The proper solution would of course be to replace the
pots with 10 kΩ pots.


Please explain the void loop() section of the sketch #include <VirtualWire.h>

int PWMB = 5; //Speed control

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

  //receiver setup
  vw_set_rx_pin(2);
  vw_set_ptt_inverted(true);
  vw_setup(2000);
  vw_rx_start();
}

void loop(){
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    int column = 0;
    String message;
    int commands[30];

    for (i = 0; i < buflen; i++)
    {
      //DEBUG:
      Serial.print(char(buf[i]));

      if(char(buf[i]) == '|'){
        commands[column] = message.toInt();
        message = "";
        column++;
      } else {
        message += char(buf[i]);
      }
    }

  commands[column] = message.toInt();
  }
}

This topic is the receiver side of my last topic: please explain the sketch attached
that one sending date and this is a receiver.

questions:

The transmitter transfer date array of [60] like: 523 | 487, here int commands[30]; just 30, is it OK?
if(char(buf[i]) == '|') / commands[column] = message.toInt();, seems just convert the date before '|'?
What is the result of message += char(buf[i]);?

Thanks

The transmitter transfer date array of [60] like: 523 | 487, here " int commands[30];" just 30, is it OK?

If you have a maximum of 59 characters (59 printable characters plus the NULL at the end equals 60), and each number is separated by a | character, then the maximum possible numbers you can have, if they are all single digit, is 30. So yes, an array of 30 integers is fine.

  " if(char(buf[i]) == '|') / commands[column] = message.toInt();", seems just convert the date before '|'?

Yes. It takes whatever has been placed in message and converts it to an integer, then empties message ready for the next number.

  what is the result of " message += char(buf[i]);"? Thanks

It adds the current character from the buffer (pointed to by i) to the end of the message string.

It's not the best way of doing it, and it can make a mess of your heap causing your Arduino to crash after a while.

Personally I would use strtok() directly on the buffer:

int i = 0;
char *part = strtok(buffer, "|");
while (part) {
    command[i] = atoi(part);
    i++;
    part = strtok(NULL, "|");
}

This of course assumes that buffer is properly NULL terminated.


Using an Atmega8 Chip with an Arduino Uno instead of an atmega328 This question is posted here as a reference question (its actually a follows  on from comments in my earlier question "How to expand program memory on an arduino?") -( Edgar Bonet suggested this question and who answered 1 below  in the comments there).

I think its a useful question to others new to arduino. I have posted an answer too. But you can of course add your answer too. I dont know everything about arduino- still learning. It does not refer to the version of the Uno that uses a surface mount atmega328-but the version with removable atmega328.

1) If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn a bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328)?  The atmega8 is of course an older chip than the 328 (and is significantly cheaper) but it still has same pinouts.

2). I am using the 16mhz crystal in my project. So using an Arduino Uno with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino Uno pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator?

3) So hw much memory is left after writing bootlader to atmega8 ?

4) Can I burn the bootloader more than once?

1) yes the arduino uno can be used with a blanked at mega8 chip with the NG bootloader burned onto it.
You would set the board as NG in the IDE to use the arduino IDE (to upload sketches and so on) with it.

2) A crystal and capacitors is still required -the same values as used for the removed atmega328.

3) The smallest bootloader will leave 7.5kb of program memory left to use on the atmega8.

4) Yes


Arduino Ethernet and Uno R3 as a firewall Is there a way to program the Ethernet Shield and Uno R3 to act as a firewall without using a huge chunk of the allowed bytes on the R3?  I plan on using a DC adapter to plug the R3 into a wall, and use the mini-SD card to keep logs while having the ethernet shield plugged into my router.

I know that it is possible to program it to do this but I want to know if there is a simple modification I can make to the web-client library or if I should use the web-server library and modify that?

As an entry level board, I wouldn't suggest trying this on the R3. You can do it to an extent on the Yun which comes with both a network port and wifi.

Now that said, your internet speed will be severely hampered by the lack of resources on the yun. In which case, you might want to steer closer to the Intel Edison, which you can use with the arduino IDE. It is considerably more powerful.


Difference between PWM and regular output port for servos? I have been controlling my servomotors for a while now only using pin 0. After some research, it has became apparent to me that the ports with ~ are the PWM pins.

I thought that all pins sent out PWM signals, therefore the motor was able to move back and forth. Now I'm really confused as to how the motor was able to turn without using a ~ pin like pin 5.

Can someone explain why I should or should not use PWM signal when controlling a motor?

Servos does not use PWM, it uses PPM:

PWM = Pulse width modulation, The pulse start at 0ms, and is high for the percentage of the time compared to the percentage of the voltage you want, 5v signal, if you want 1v, the pulse is 20ms High and 80ms Low.
PPM = Pulse position modulation, The pulse length is always 5ms High and 95ms low, but the interesting part is if high starts after 5ms or 50ms (or any other).

So PWM is to lower voltage, PPM is a signal pulse.

This means that no matter what port you are using on the arduino you are able to control a servo since you only need High or Low, and not a lower voltage.

What you need to be aware of in this case is on the arduino is a PPM signal is using up a timer. The arduino has 3 timers where of 2 is available, one is used internally. Though there is code where you can attach up to 3 servos on the same internal timer.


Multiple VL6180X distance sensors interactive problem I am trying to use a VL6180X distance sensor and an Arduino Uno board for individual sensor doing individual distance sensing. This sensor follows the I2C protocol. Since for the same type of sensor, the I2C protocol says that they would all have the same address, I am thinking about using the chip enable pin (GPIO00) on the sensor chip to toggle sensor when doing the distance measuring.

I am able to update the address of the sensor group now. But I think to obtain individual results from different sensors on the Arduino serial monitor, right now I can only do one time setup sensor thing (like I couldn't update and toggle around different sensors). Once I started to do that, the results from the serial monitor were wrong. Any advice how I can continue to toggle around the sensor and make them work using the GPIO00 pin?

The code I'm using is:

#include <Wire.h>
#include <VL6180X.h>
#define Address1 0x20
#define Address2 0x22
#define Address3 0x24

VL6180X sensor;

int pin2 = 2;
int pin3 = 3;
int pin4 = 4;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  pinMode(pin2,OUTPUT);
  pinMode(pin3,OUTPUT);
  pinMode(pin4,OUTPUT);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
  sensor.init();
  sensor.configureDefault();
  sensor.writeReg(VL6180X::SYSRANGE__MAX_CONVERGENCE_TIME, 30);
  sensor.writeReg16Bit(VL6180X::SYSALS__INTEGRATION_PERIOD, 50);
  sensor.writeReg16Bit(VL6180X::INTERLEAVED_MODE__ENABLE,0);
  sensor.setTimeout(500);
  sensor.stopContinuous();
  delay(300);
  sensor.startInterleavedContinuous(100);
}

void loop() {
  hello2();
  delay(1000);
}

void hello1(){
  sensor.setAddress(0x29);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address1);
  sensor.writeReg(0x212,Address1);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 1: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 1: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
}

void hello2(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address2);
  sensor.writeReg(0x212,Address2);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 2: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 2: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

void hello3(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address3);
  sensor.writeReg(0x212,Address3);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,HIGH);
  Serial.print("Ambient 3: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 3: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

Any help would be appreciated!

You can use an I2C multiplexer (TCA9548A). One I2C input can be output to one of the eight I2C outputs.

It has 8 configurable addresses, so you can connect 64 I2C devices with the same address by using 8 multiplexer chips.


Opto Isolator question I'm building a CANBUS network based on an arduino to go into an offroad racing truck. The vehicle has two separate battery systems, and I would like to monitor the voltage while still electrically isolating them from the arduino itself. For the voltage monitoring itself, I assume I can use a simple voltage divider into an Analog pin. To electrically isolate the arduino, would an Opto Isolator work? I found this one: https://www.sparkfun.com/products/9118 But it appears that it's designed for low voltage to control high voltage, as opposed to the other way around.

An optoisolator is good for digital signals, but won't transfer an analog signal accurately.

Instead, you could put ADCs on the different circuits and optoisolate their communication with a master Arduino.


How to transmit data from Arduino to Raspberry Pi? I am planning to build a network with five Arduino Mega devices, each of which will collect data using multiple sensors. Each Arduino will periodically transmit the sensor data to a gateway Raspberry Pi using XBees. As it is the first time I am working with Arduino and Raspberry Pi, I need help with the following:

Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions that I can use for this purpose?
Does MQTT, Node-RED or Node.js have any role in the above?

Thank you for your advice!

A.

Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions which I can use for this purpose?
  Does MQTT, Node-RED or Node.js have any role in the above?

I have searched, explored, read and found that MQTT can be used to send and receive data from Arduinos to RaspberryPi as in [1] and [2]. So, no need to design and develop a new protocol.

MQTT libraries, such as PubSubClient [3] are available for Arduino. So Arduino code can use these libraries and no need to write much code either.

Simple and straight!

A.

[1] https://funprojects.blog/2018/03/04/arduino-talking-mqtt-to-node-red/

[2] https://iotdesignpro.com/projects/interface-arduino-with-node-red-to-send-sensor-data-on-webpage

[3] https://www.arduinolibraries.info/libraries/pub-sub-client


A proper way to get the roll, pitch and yaw values TL, DR : What is the method(in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant.

I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.

I think I also have some problems about understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the attitude of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.

What I want is to be able to know at any instant:

what is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
what is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
what is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing x tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements(different axis orientations of the sensor).

I also have basic understanding about what a gyroscope is.

I have an MPU6050(Accelerometer+Gyroscope).

Thanks in advance.

P.s : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.

First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.

Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis:
Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.

This is different from the last result: order of rotation matters.

  I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).

When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).

As you can see from the following image, the angle of rotation θ = atan2(x, z).

The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).

Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.

Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used Sebastian Madgwick's algorithm for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.

Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.

Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.

It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.

If you want to, you can also get the quaternion from the acceleration vector directly:

    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
         * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
         * where (x y z) is a unit vector representing the axis about which
         * the body is rotated; ϑ is the angle by which it is rotated.
         *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
         * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
         */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }


Arduino Interrupts Classes and Namespace I'm working inside the Arduino IDE environment and have made a class that builds on the Adafruit RDG LCD with interrupts While looking at how to combine the Attach Interrupt() into my class I came across this post about using namespaces

Why make a class then? What about a namespace?
A class with one instance is like a group with one person in it.
-nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial I've found is here, but I don't see how I would mix in the Attach Interrupt() function
Right now, my code looks like
/**** Pre-Setup *****/
#define Menu_PIN 3
voltile bool flag;

//Init Class
class LcdMenu : public Adafruit_RGBLCDShield
{
  public:
  MenuFoo()
}
LcdMenu LcdM;

//run Setup
void setup()   /****** SETUP: RUNS ONCE ******/
{
  pinMode(Menu_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
}

void loop()
{
  if(flag){
    LcdM.MenuFoo();
    flag=false;
  }
}

//Handles Inturrupts for Class
void ProcMenu()
{
  flag=true;
}

//define MenuFoo
void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the ProcMenu() function making my code easier to read/maintain.

In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have one single handler for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for this instance), but it can be
a static method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.

I would try something along these lines:

class LcdMenu : public Adafruit_RGBLCDShield
{
public:
  LcdMenu();
  void begin([params]) {
    Adafruit_RGBLCDShield::begin([params]);
    attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
  }
  void MenuFoo();
  void update() {
    if (flag) {
      MenuFoo();
      flag=false;
    }
  }
private:
  static volatile bool flag;
  static void handleInterrupt() { flag = true; }
}

volatile bool LcdMenu::flag;

Then you just have to call LcdM.update() in loop().


Errors when compiling the GSM SMS receive example from the Arduino IDE I want to receive SMS and check whether the character is 'y' or 'n'. If it is 'y', set a pin to high so that a light glows. I thought I could use the example code given in the Arduino IDE for receiving SMS, but when I compile (without connecting the board, using ctrl+r) it shows the following errors:

Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

In file included from F:\Arduino\libraries\GSM\src/GSM.h:46:0,
                 from F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:21:
F:\Arduino\libraries\GSM\src/GSM3ShieldV1BandManagement.h:49:125: warning: 'typedef' was ignored in this declaration
 typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
                                                                                ^
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino: In function 'void setup()':
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:47:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
     if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
                                  ^
Sketch uses 13322 bytes (41%) of program storage space. Maximum is 32256 bytes.
Global variables use 996 bytes (48%) of dynamic memory, leaving 1052 bytes for local variables. Maximum is 2048 bytes.
An error occurred while uploading the sketch
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Please help me rectify the error.

I use a SIM900 GSM board. I connect the tx and rx of the GSM board to the Arduino's tx and rx.

Those are warnings, not errors.  The code should have compiled and be able to flash.


How to Connect ESP8266 with ultrasonic sensor and dht11 without breadboard? I want to connect the sensors in Esp8266 after I code those using arduino uno r3. The problem is that I don't have the idea on connecting those sensors without breadboard. Thank you

If you do not want to use a breadboard, you could solder the wires together of tie them together, so long as none of the wires which aren't supposed to be touching are touching. Or you can also use flex tape! (Don't mind my meme)


Stuck making multi, many button, joysticks I'm stuck, I figured I'd ask here for some help... Note I'm a newb and this is essentially my first Arduino project beyond blink...

I'm creating Virtual cockpit panels for DCS World, using an Arduino Leonardo as an HID device. I'm using three SN74HC165 Shift-In registers for multi-buttons (24) - as it seemed the easiest - and all in all it does work...

So I figured that I'm using only 4 pins on the Leonardo, so why not try to setup 3 of these "shift-in clusters" (12 pins) to appear as 3 separate joysticks?

I got the one working and I got 2 more joysticks showing up in Windows10... now my problem is: how would I setup 2 more "shiftIn Clusters", I've tried many things but I must defer to outside help (cause I really don't know what I'm doing)

Edit to clarify: So each joystick need 3 or 4 shift registers making 24-32 buttons on each joystick

Shift In Lib: https://github.com/…/Ardu…/blob/master/ShiftIn/src/ShiftIn.h

Joy2 Lib: https://github.com/MHeironimus/ArduinoJoystickLibrary

Here's an image of the Layout I want: https://i.imgur.com/eZfMMzI.png

... any help would relieve a great headache, Thank for your time

#include <ShiftIn.h>
#include <Joystick.h>

// use <n> shift registers
ShiftIn<3> shift;             // use three shift register

// Create joystick
// TESTING MULTI JOYSTICKS
// 1/3 Works!!!
// 3/3 Appear in Windows
// ????? must add shiftIn sections for 2nd and 3rd joysticks????
// (add pin usage + modify line 77-79 stuff)

#define JOYSTICK_COUNT 3
Joystick_ Joystick[JOYSTICK_COUNT] = {
  Joystick_(0x03, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x04, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
  Joystick_(0x05, JOYSTICK_TYPE_GAMEPAD, 32, 0, false, false, false, false, false, false, false, false, false, false, false),
};

// Set to true to test "Auto Send" mode or false to test "Manual Send" mode.
//const bool testAutoSendMode = true;
const bool testAutoSendMode = false;

const unsigned long gcCycleDelta = 1000;
const unsigned long gcAnalogDelta = 25;
const unsigned long gcButtonDelta = 500;
unsigned long gNextTime = 0;
unsigned int gCurrentStep = 0;
int gJoystickId = 0;

/*
// WORKING SECTION Single Joystick with Shift Reg
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_GAMEPAD,
  32, 0,                        // Button Count, Hat Switch Count
  false, false, false,          // X and Y, but no Z Axis
  false, false, false,          // No Rx, Ry, or Rz
  false, false,                 // No rudder or throttle
  false, false, false);         // No accelerator, brake, or steering
*/

void setup() {

  shift.begin(8, 9, 11, 12);  // set pins of the shift register
//  shift[1].begin(7, 6, 5, 4);  // set pins of the shift register
//  shift[2].begin(3, 2, 1, 0);  // set pins of the shift register

 Joystick[0].begin();
 Joystick[1].begin();
 Joystick[2].begin();
}

void loop() {

  if (shift.update()) {
    for (int i = 0; i < shift.getDataWidth(); i++)
    Joystick[0].setButton(i, shift.state(i));            // just press or release the button
  }
/*if (shift[1].update()) {
    for (int i = 0; i < shift[1].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[1].state(i));            // just press or release the button
  }
if (shift[2].update()) {
    for (int i = 0; i < shift[2].getDataWidth(); i++)
    Joystick[0].setButton(i, shift[2].state(i));            // just press or release the button
  }
  delay(10);
*/
}

Each ShiftIn instance handles just one connection. You need to make multiple instances.

ShiftIn shift1<3>;
ShiftIn shift2<3>;
ShiftIn shift3<3>;

Then you begin each of them:

void setup() {
    shift1.begin(8, 9, 11, 12);
    shift2.begin(7, 6, 5, 4);
    shift3.begin(3, 2, 1, 0);
    ... etc ...
}

Each shiftx is a completely separate entity. You can just repeat your block of code for each shift object:

if (shift1.update()) {
    for (int i = 0; i < shift1.getDataWidth(); i++)
    Joystick[0].setButton(i, shift1.state(i));
}

if (shift2.update()) {
    for (int i = 0; i < shift2.getDataWidth(); i++)
    Joystick[1].setButton(i, shift2.state(i));
}

if (shift3.update()) {
    for (int i = 0; i < shift3.getDataWidth(); i++)
    Joystick[2].setButton(i, shift3.state(i));
}

You could arrange the ShiftIn objects into an array like you do with your Joystick objects and then loop through them, but that is pretty pointless for just three of them.


Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors? I am using PWM (analogWrite) with a common anode LED. My previous experience is using a common cathode. My breadboard is as shown:

simulate this circuit – Schematic created using CircuitLab

This creates a semi-bright white (ugly red-green-blue mixture) like I expected. I am using only one PWM output (It is currently fading).

Now, what I ask is how can I use multiple PWM outputs to make different colors display without transistors? I was thinking that I could have 3 dedicated pins on the Arduino that switch from ground to floating extremely fast, but is there an easier way?
If not, a little explanation on how to do it with transistors (mostly just a small wiring diagram) would be great. Cheers!

As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

simulate this circuit – Schematic created using CircuitLab

Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.

Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.


Components required to control the Speed of Wilo Para AC Synchronous Motor I want to control the speed of the AC motor based on the temperature set on the Nextion  HMI. Right now I have my ESP32 Microcontroller and Solid-state relays which supply the maximum output power of 10 amperes. My Wilo Motor requires the power of 0.03 to 0.66Amps. I am in a state of confusion about what component is required in the middle to connect my ESP32 Controller to send the analog PWM control signals of 0 to 10V to my Wilo Para Motor for the speed control. I searched in Google and I got few data like H-Bridge, PWM Speed control manual module. I'm stuck in this work and I'm looking for help.

Below I have attached the link of the datasheet. On page number 34 is my WILO Para Motor and the model name is Wilo Para 25-180/9-87/IPWM1 in the table

https://wilo.cdn.mediamid.com/cdndoc/wilo164576/1544113/wilo164576.pdf

Thanks in Advance.

You do not want a "0-10V PWM signal". There is no such thing.

There are generally 2 methods of controlling motors like these:

Through a variable analog voltage between 0V and 10V, where the voltage given is proportional to the speed, and
Using a digital PWM signal where the duty cycle is proportional to the speed.

You are getting confused and combining the two together (and to be honest that datasheet, which is really little more than a sales brochure, doesn't help matters).

Typically a PWM input on a motor uses a standard TTL signalling method.  This specific motor, as detailed in this document uses a slight modification on the standard. It requires a minimum of 3.6V for a HIGH, and the ESP32 gives 3.3V maximum.

Because of that you will need to amplify, or "boost" the signal to a slightly higher voltage.  The simplest way to do that is with an off-the-shelf logic level translator (3.3V to 5V). There are cheap MOSFET based ones on eBay etc that will do the job.

If you want to create your own the circuit is quite simple, and requires one N-channel MOSFET and two resistors. I use the BSS138:

simulate this circuit – Schematic created using CircuitLab


Connecting Arduino to the ESP8266 I want to run more stepper motors and would like to know if there is a way to connect the Arduino and the ESP8266 NodeMCU together for more functioning.

Absolutely. I'll use the Arduino UNO and the ESP8266-01 WiFi module as an example:

The ESP8266 works with 3.3V and not 5V, so you need to connect the 3v3 pin on the Arduino to the VCC and CH_PD pins on the ESP8266.
Connect the GND pin on the Uno to the GND pin on the ESP.
Connect the RESET pin on the Uno to GND. Grounding the RESET pin
effectively causes your Arduino to work as a dumb USB to serial
connector (which is what we want to talk to the ESP8266).
Connect the CH_PD pin on the ESP8266 to the 3.3V line
Connect the RXD pin on the Arduino Uno to the RX pin of the ESP8266.
Connect the TXD pin on your Arduino Uno to the TX pin of the
ESP8266.

Normally, when you want two things to communicate over serial, you'd connect the TX pin of one to the RX of the other (send --> receive). In this case, however, the Arduino isn't talking to the ESP8266; the computer is talking to the ESP8266 via the Arduino.


The IDE says my (brand new) Arduino UNO is on COM 1 I recently bought an Arduino Uno and installed everything necessary. I tried it on both USB ports on my computer. However, the Ports menu only shows COM1. There is a line on the bottom of the IDE which says Arduino Uno on COM1.

Any program I try fails to upload to the board. When I tried the Blink example, the following error message appeared:

Arduino: 1.6.3 (Windows 7), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for
local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x43

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x43

and so on. Until,

This report would have more information with
"Show verbose output during compilation" enabled in File > Preferences.

I have a Windows 7 64 bit desktop.

Any help will be appreciated.

Here are a few troubleshooting tips:

First check if the board is listed as Arduino Uno in the IDE by going to Tools --> Board
Check this site.
Also, try reinstalling the driver.
Check your cable.
As a last resort you can try re uploading the bootloader.


Return a char concatenation My goal is to create a function that concatenate 2 chars into 1, and return it as MQTT subscribe. I get a difference between the results inside and outside the function ( I'm new to Arduino ), and I can't find why:

Code:

// Update variable below:
const char *direction = "up";
const char* clientID = "Sonoff";

//Consts
const char *client_temp = "HomePi/Dvir/Windows/";
const char* outTopic = "HomePi/Dvir/Messages";
//const char* outTopic2 = "HomePi/Dvir/Windows/ESP32";
const char* inTopic2 = "HomePi/Dvir/Windows/All";
char *inTopic;

void setup() {
  Serial.begin(9600);
//  len(create_topic(client_temp, clientID));
  inTopic = create_topic(client_temp, clientID);
  Serial.println(inTopic);
}

char *create_topic(char *chr1, char *chr2){ .   // added *
  char topic[strlen(chr1) +strlen(chr2)+1];
  sprintf(topic,"%s%s",chr1,chr2);
  Serial.println(topic);
  return topic;
}

void loop() {
  // put your main code here, to run repeatedly:

}

Result ( both line should have been same):

HomePi/Dvir/Windows/Sonoff
⸮⸮,茗⸮;⸮_⸮%⸮l?⸮az⸮z⸮%⸮⸮⸮\;⸮m⸮

The concatenation is working fine in both instances.

What is wrong, though, is that you can't return a pointer to a locally declared array from a function. That array no longer exists when you leave the function.

The thing to remember with arrays is that you never pass the actual array to or from a function. All you pass is a pointer to the memory address where the array is.  If you allocate an array in a function that memory is allocated on the stack. When you return the array from the function you return an address that is (currently) within the stack.  When you leave the function all memory allocated on the stack by that function is removed, and that includes your array.

There are four ways of solving the problem - all of them have their pitfalls.

Use a global "scratch pad" array that is big enough for any concatenating you may want to do. Do your concatenation in there.
Declare your array static, which means it's allocated only once and can be returned from the function - but like the global one you have to have a fixed size.
Pass a pointer to a suitably sized array to your function to have that array used for the concatenation, and
Allocate memory on the heap using malloc().

My normal method is number 3. It's the safest and most flexible:

const char *a = "part a";
const char *b = " part b";

char all[14];
doConcat(a, b, all);

void doConcat(const char *a, const char *b, char *out) {
    strcpy(out, a);
    strcat(out, b);
}


Arduino Mega2560 clone responding slowly I am using an Arduino Mega2560. Using Arduino Mega as ISP to burn sketch, I had loaded the bootloader from Arduino IDE.

I uploaded the blink LED code to the Mega. But the LED is responding slowly. Same with Serial code. Delay of 0.1 second acting as 1 second on my board. In code serial communication baud-rate is 9600 but I am getting proper value when I set the baud-rate to 4800 in serial monitor.

Could anyone point out the problem?

Either your fuses are wrong (set to 50% the real speed of your crystal / ceramic resonator), you're using the internal oscillator instead of the expected external one, or you have the wrong board with the wrong F_CPU value selected in the IDE.

Check all of those carefully.


How to create a wired ESP8266 range extender? Context: I have a NETGEAR router on the first story of my home, the range doesn't extend to the ground floor. I do have a cable duct from my router(on the first story) to the ground floor.

Question:

Is it possible to wire a Keyes ESP8266 to my router to act as a WiFi range extender?

Note: The length of the cable would be 10 meters.

There's a project that calls itself a "wifi repeater" at

https://github.com/martin-ger/esp_wifi_repeater

It includes support for an ENC28J60 ethernet adapter connected via SPI.

It has some serious limitations.

First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.

Also, devices on the original network will not be able to originate connections to devices on the extended network.

But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.

Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.

Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.

I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.


Difference in increment & decrement loop execution speed I was experimenting with for loops when I noticed that a simple increment loop executes faster than a decrement loop. I can't think of any reason why it should be like that. Is there something in my code that is causing the different in execution speed?

The code is as follows:

// Global Variables
const int spk = 7;
const int led = 6;
int j = 0; // counter variable

void setup() {

  pinMode(spk, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
} // end of setup

void loop() {

  tone(spk, 300, 500); // first note with duration

  // increment loop
  for (j=0; j <= 500; j = j + 1) {
    digitalWrite(led, HIGH);
    Serial.println(j);
  } // end 1st note loop

  tone(spk, 100, 500); // second note with duration

  // decrement loop

  for (j = 500; j >= 0; j=j-1) {
    digitalWrite(led, LOW);
    Serial.print("the value is=");
    Serial.print("\t");
    Serial.println(j);
  } // end 2nd Note loop

} // end setup

Comment out these 2 lines

Serial.print("the value is=");
Serial.print("\t");

And report back on the speed difference.
Why not add a reading of micros() before and after each loop and see how much difference there really is?  All time variables are unsigned long.

startTime = micros();
// your loop
endTime =  micros();
duration = endTime - startTime;
Serial.println (" "); // line break
Serial.print ("duration in uS = ");
Serial.println (duration);

I edited to add some missing )s and a 2nd line break.


Problem with LCD keypad shield and Arduino Uno R3 I have a problem with powering my LCD Keypad Shield from a DC cable (4 AA batteries or 9V battery). Everything looks good, but the LCD screen doesn't display anything. When I used a USB cable, the screen works as it should.

What is the problem?

I do not have an answer... but it might be power consumption problem, ou voltage stability problem. I use a LCD shield with an RFID card reader (contactless card reader like you can find in the subway). When I plug the thing to a 9v battery the contrast is higher than when I connect it to an USB cable.


How to connect an lcd i2c using only pins A0 and A1 (SDA, SCL, GND, and VCC are given) I want to know how to connect an lcd i2c, with an led 8x8 matrix at the same time. The problem is, all the analog in pins are used, except A0 and A1. Using this tutorial:
https://www.makerguides.com/character-i2c-lcd-arduino-tutorial/
It says I must have analog pins A0-A2 with nothing connecting, except I have A2 connected, which is why both screens don't work right. So how can I use only pins A0-A1 with an lcd i2c? Thanks.

You may be finding Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered) confusing.  These refer to the I2C address selection lines of the IO expander (the PCF8574T) used on the I2C LCD display and not to the A0-A2 analog pins of the Arduino itself.

The note // Wiring: SDA pin is connected to A4 and SCL pin to A5. is referring to the analog pins of an UNO (or Nano) because these pins also happen to carry the ATMega328P's I2C ("Wire") signals.
So there's nothing about using the I2C display that prevents you from using the Analog A0-A2 pins of the Arduino for other purposes.  Only the  Arduino's A4 and A5 pins are used to carry I2C/Wire.


How do I get the Itead 3G shield to work? I've tried a pretty standard code but the Serial Monitor yields zero response.

Using a standard Arduino Uno (tried a second one as well, just to be sure) and am now trying the second shield with this code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

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

}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

There is nothing coming back whatsoever in the serial monitor (yep, I checked the baud rate and tried several others).

Any ideas?

What should I be seeing if anything?

What should I be seeing if anything?

Usually, a GSM module will not send (unsollicited) messages. Everything it sends will be an response to an received message.

Try sending AT (with a new line/carriage return (depending on the GSM module)) to the GSM module, it will send something like AT OK or just OK

And you didn't set the pin directions (output/input), might be doen by the serial libraries, but beter be safe if you're not sure.

Also check your wiring (jumpers on UART multiplexer in this case?) and share it with us, Rx/Tx wiring often gets messed up :)
If your GSM module has a USB connection, you might even test it with a terminal (taking out the Arduino in the middle, thus any wiring/code between.)

I also suggest you change the name of the serial connection to the GSM to something like gsmSerial rather than mySerial (which could be anything).

Be sure the 3G shield has enough power (amperes), otherwise they might reset when attempting to make an connection.
(Put the external supply in the Arduino, rather than USB powered)


Embedded-c, schedule a function? Simple question, of course if you do this

FunctionA();
Delay(1000);
FunctionB();
FunctionC();

it will call A, then wait a second, then call B, then call C.

How does one do this? ...

FunctionA();
.. Invoke FunctionX one second from now ..
FunctionB();
FunctionC();

So, I want it to do A, then without stopping continue to B and then C.  Later (one second later) it will do X.

Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:

// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015

typedef void (*GeneralFunction) (); // function pointer type

GeneralFunction wantedFunction = NULL;  // function to call
unsigned long functionTimerStarted;     // when the timer started
unsigned long delayPeriod;              // how long to wait (ms)

void functionA ()
  {
  Serial.println ("Function A");
  }  // end of functionA

void functionB ()
  {
  Serial.println ("Function B");
  }  // end of functionB

void functionC ()
  {
  Serial.println ("Function C");
  }  // end of functionC

void functionX ()
  {
  Serial.println ("Function X");
  }  // end of functionX

void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
  {
  wantedFunction = f;
  functionTimerStarted = millis ();
  delayPeriod = when;
  }  // end of scheduleFunction

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

  functionA ();  // call this now
  scheduleFunction (functionX, 2000);  // call this later
  functionB ();  // call this now
  functionC ();  // call this now

  }  // end of setup

void loop ()
  {
  // see if time to call the delayed function
  if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
    {
    wantedFunction ();
    wantedFunction = NULL;  // don't call it again
    }  // end of if time up

  // do other wanted stuff here

  }  // end of loop

This uses:

A function pointer to remember which function to call in the future.
A global variable to remember when you wanted this timing interval to start.
A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:

  scheduleFunction (functionX, 2000);  // call this later

Then in loop() we see if the time is up, and then call the function.

This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.

You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.

For more information about function pointers, see Function pointers / function callbacks / function variables.


Is it possible to transmit using an NRF24L01+ without an Arduino? I have two NRF24L01+ modules which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.

That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?

To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.

Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.

The nRF24L01+ has a somewhat complex SPI based interface, where many registers have to be configured and tested and timeouts honored.  Therefore it requires some kind of microcontroller to send or receive even the simplest message.

This can be as simple as a 3.3v Arduino Pro Mini (less than $3 with shipping), and there are libraries which simplify the task of interfacing to it - in particular see the RF24 library (there are many variations, see https://github.com/TMRh20/RF24 for a good one).

But many other microcontrollers could work as well.

Once you bite the bullet and accept the need for a microcontroller, yes the code can identify the source of the signal (which pushbutton) and much, much more.

Or you could use a dedicated device like an xBee which can be configured using a Windows utility to send the state of an input pin to another xBee; basically there is already a programmed microcontroller on the module along with the radio (not nRF24L01+ compatible).


toggling Rx, Tx pins after Serial.begin What should one expect when the following program runs on Arduino Uno?

void setup()
{
    Serial.begin(9600);
    DDRD |= 0b11;
}

void loop()
{
    PORTD |= 0b11;
    delay(100);
    Serial.print("ABCD");
    PORTD &= ~0b11;
    delay(100);
    Serial.print("DEFG\n");
}

When Serial.begin() is used, the pins PD0, PD1 might be configured as UART pins. After that if DDR is used, are the pins configured as GPIO, or are they still UART Rx, Tx pins?

As always, the answer is in the datasheet:

  TXD/PCINT17 – Port D, Bit 1

  TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
  PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.

  RXD/PCINT16 – Port D, Bit 0

  RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show.  It's not defined in the datasheet (because who would do it?)


Pass custom element of an array from an inherited class to main sketch I'm building a base class that creates color patterns using FastLed's CRGB structure. I use the base class as inheritance for another more specific class that modifies a vector of colors (Pixels[]) and at some point I want to pass the color of a specific element from my class to the main sketch. But i'm having some issues with it, since the content of Pixels[] doesn't seem to match what I actually write in there.

Pattern.h:

class Pattern
{
    public:
    CRGB PixelAt(int idx);
    CRGB Pixels[6];
}

Pattern.cpp:

CRGB Pattern::PixelAt(int idx)
{
  // safety check
  if (idx >= 0 && idx < NumLeds)
  {
    return Pixels[idx];
  }
  else
  {
    Serial.print("Index out of bounds: "); Serial.println(idx);
    return CRGB::Black;
  }
}

TestPattern.h:

class TestPattern : public Pattern {
    void Tick(unsigned long millis);
}

TestPattern.cpp:

void TestPattern::Tick(unsigned long millis)
{
    for (int p = 0 ; p < NumLeds ; p++)
    {
      Pixels[p]=CRGB::Blue;
    }
}

Main Sketch:

for (int p = 0; p < NUM_PATTERNS; p++)
{
  // update pattern
  ledPatterns[p].Tick(millis());

  if (ledPatterns[p].Status == Enabled)
  {
    // sum the values of the pixels
    for (int l = 0; l < NUM_LEDS; l++) {
      leds[l] += ledPatterns[p].PixelAt(l);
    }
  }
}

I'm skipping parts of the code to make it easier to read, but I think with this much you should be able to help me make it work. I'm still getting acquainted with C and pointers, which is where I think the problem lies.

So how should I declare and use Pixels[] so that the Main Sketch, the base class and the inherited class all have consistent information?

After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me find the problem.

I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:

Pattern ledPatterns[NUM_PATTERNS];
ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p].Tick(millis());
...

When i later called ledPatterns.Tick (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.

This is how i should have been initializing the patterns, since they are inherited:

Pattern* ledPatterns[NUM_PATTERNS];
ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p]->Tick(millis());
...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code


What is the minimum wattage of resistors for breadboarding with Arduino Uno? I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?

The answer is: It depends what you want to use them for.

You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them.  There are standard formulae that tell you the power in any given situation.

For instance, if you know the current and the resistance you can use:  P=I²×R. If you know the voltage across the resistor it's P=V²÷R.

Take as an example the common resistor for an LED.  Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.

To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors.  ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.


How to Connect Dc motor with encoder (pololou) with motor shield and Arduino Mega 2560? I tried to search a bout how to connect plolou motor with encoder to arduino mega and the motor control shield as in those pics  if any one knows how to connect those to each other please tell me

A quick look on Pololu's website reveals that:

    Color   Function
  --------  --------------------------------------------
    Red     motor power (connects to one motor terminal)
    Black   motor power (connects to the other motor terminal)
    Green   encoder GND
    Blue    encoder Vcc (3.5 – 20 V)
    Yellow  encoder A output
    White   encoder B output

Thus: Red goes to M1A and Black goes to M1B on the motor shield.
The remaining wires are for the encoder and go to Arduino pins.
Green goes to Arduino GND, Blue goes to 5V, Yellow and White go to the
digital i/O pins of your choice.

Note: Your motor shield has extra 5V and GND pins so you can connect the Blue and Green wires there.


How do I include a file that is not a .h, .c or .cpp file? I am using the ADF7030 on the breakout board (not motherboard) and I am trying to interface it with an Arduino Uno. I want to load the transceivers configuration file onto the chip using SPI. To do this, I need to include the ".cfg" file but when I use the C style array (as in the datasheet - code below) it says that it can't find the file in the .ino sketch.

const unit8_t Radio_Memory_Configuration [ ] = {
     #include "Settings_ADF7030-1.cfg"
}

How could I include this file?

From looking at the arduino-builder source only files with the following extensions are copied to the build directory: .ino .pde .h .c .hpp .hh .cpp .s

So you will need to use one of those extensions.


Detect if a 3 phase AC submersible pump is on I need to know when a 3 phase AC submersible pump is turned on, for the sake of logging it to a online database. Thing is, I do not know how tell if it is ON, or OFF. I've given a thought to using a current transformer, specifically the "STC-013-30" one, but it requires to be wrapped around one of the AC wires (live/neutral) but the motor i have has both the wires insulated together forming a single, huge wire. Plus, its 3 phase, and I do now know if the STC can detect 3 phase currents. Can it be done some way? Can I utilise some other tool to tell if the motor is ON?

It's likely that the power to the motor is originating at a panel with breakers. You should be able to confirm that only one breaker set is being used to power the pump motor. At that location, all the wires are separated.

If you do not have the necessary skill to identify the correct wires, consider to consult an electrician. It is advisable to remove power to the panel before you begin to insert your fingers to wrap the sensor wire around the correct lead.


Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration I'm in the echopen association, our goal is to create a low cost, open source echographic probe. In order to do that, we use an arduino due for the first step. For doing acoustic imaging, we use ultrasonic transducer wich works at high frequency, typically 5 MHz. So, for our purpose we need to send and receive analogic signal at high frequencies.
We want to connect a 80 Msps DAC and a 80 Msps ADC to the arduino due so we can generate and mesure analog signal up to 42 MHz. I have found here (http://www.instructables.com/id/Arduino-Timer-Interrupts/#step0) how to use arduino timer interrupts in order to send and receive data at 84 MHz. I haven't connect my converters for the moment, but I have preliminary questions.
First, is the definition of the timer is the same for the arduino due (i.e. timer1 is a 16 bits timer) ? Morever, my ADC and DAC are 14 bits converters, can I tell to the arduino to sent only 14 bits digital signal ?
Secondly, as we work at high frequencies we will have to send a lot of data from the microcontroller to a computer via the serial port. I have make a test and at 250000 bauds it takes nearly 0.5 second to transfer 4300*8 bits datas. It is to slow for our purpose, how can I do it faster ?

If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due.  If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers.  Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS.  I haven't read the DMA section closely enough to verify that this will work with the M3.

See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA.  Also see the eevblog.com page, “Looking for Cortex M3 or M4 with DMA to GPIO capability”.


Reading an MCP23S17 I/O expander port with the Arduino SPI library I am trying to read an MCP23S17 I/O expander port B with the Arduino SPI library.
The following example is simple as possible, and I still can not get it to work.

The setup is an MCP23S17 I/O expander on a Teensy LC controller.
MCP23S17 port B pins are alternately grounded and energized.
I confirmed the pin voltages with a multi-meter.
Variable portBState is a bitwise reading of port B, and printed.

Expected output is:

10101010

Actual output is:

11111111

Sketch:

#include <SPI.h>

const uint8_t ADDR = 0x20;      //MCP23S17 address, all 3 ADDR pins are grounded
const uint8_t OPCODE_READ  = (ADDR << 1 | 0x01); //MCP23S17 read command

const uint8_t IODIRB = 0x01;
const uint8_t GPIOB  = 0x13;

uint8_t portBState = 0;                 //bit wise

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

    pinMode(SS, OUTPUT);                //configure controller's Slave Select pin to output
    digitalWrite(SS, HIGH);             //disable Slave Select
    SPI.begin();

    //IODIRB register is already configured to input by default

    SPI.beginTransaction(SPISettings (SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE0));
    digitalWrite(SS, LOW);              //enable Slave Select
      SPI.transfer(OPCODE_READ);        //read command
      SPI.transfer(GPIOB);              //register address to read data from
      portBState = SPI.transfer(0);     //save the data (0 is dummy data to send)
    digitalWrite(SS, HIGH);             //disable Slave Select
    SPI.endTransaction();               //release the SPI bus

    Serial.println(portBState, BIN);    //should print 10101010
}

void loop() { }

Why is the output not "10101010"?

The controller is Teensy LC (3.3 volts) on Arduino 1.6.7.
SPI library: https://www.arduino.cc/en/Reference/SPI
More links in the comments below (I don't have enough reputation points to post more links in the question).

It's working now.  Here is what was missing:
A yellow jumper from the micro-controller MOSI pin to the MCP23S17 SO pin.
So the read command can travel from micro-controller to MCP23S17.


Arduino uno r3 not powering up i bought two arduino uno r3 card (not original)
one is working perfectly:

the other is not powering up (no led is lit), i did some measuring and i found that two usb connector pins on the board are shorted, how can i proceed to repair it taking in account that it works from time to time !

thank you
More images:

It looks as though there may be material between at least one USB pin and the ground layer. This may be flux of solder 'splash'.

If visual inspection shows that this may be the case I would try carefully scratching with a sharp poibt (eg scriber) along at least the green arc on the image below. Be careful not to break intended conduction paths (eg as shown in black).


Arduino nano & pro micro SPI simple communication I'm working with Arduino boards with AVR C coding to perform simple SPI communication from master for simple blink application on slave side.

They don't work, the TX function on the master side doesn't seem to work, after serial monitor debugging is discovered the function never get over the while loop! Why is that?

Here are the codes I worked on last night:

Master:

/* nano board is the Master and transmit
  data to slave to blink LEDs */

void SPI_Init(void);
void SPI_TX(uint8_t data);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  void SPI_Init();
  delay(100);
  Serial.println("SPI intialization is complete");
}

void loop() {
  uint8_t d = 0x20;
  SPI_TX(d);
  Serial.println("just sent the 1st byte");
  _delay_ms(400);
  d = 01;
  SPI_TX(d);
  Serial.println("just sent the 2nd byte");
  _delay_ms(400);
}

void SPI_Init(void)
{
  DDRB = (1 << DDB3) | (1 << DDB1); // DDB2 MOSI, DDB1 SCK
  SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
}

void SPI_TX(uint8_t data)
{
  SPDR = data;
  while (!(SPSR & (1 << SPIF)));
}

-------------------------------------------------------------- -

Slave:

-------------------------------------------------------------- -

/* pro micro as slave and receives data then push them on
  PORTD and PORTB to blink LEDs */

void SPI_Init_S(void);
void SPI_RX(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  SPI_Init_S();
  delay(100);
  Serial.println("SPI intialization is complete");
  DDRD = (1 << DDD5); // TX LED as output
  DDRB = (1 << DDB0); // RX LED as output
}

void loop() {
  // put your main code here, to run repeatedly:
  SPI_RX();
  PORTD = SPDR;   // blink the TX LED on pro micro board
  _delay_ms(500);
  SPI_RX();
  PORTB = SPDR;   // blink the RX LED on pro micro board
  _delay_ms(500);
}

void SPI_Init_S(void)
{
  SPCR = (1 << SPE) | (1 << SPR0);
}

void SPI_RX(void)
{
  return SPDR;
}

void setup() {
// put your setup code here, to run once:
 Serial.begin(9600);//start Serial
 Serial.println("Setting Up");
 void SPI_Init(void);   // <---------------- this is wrong!
 delay(100);
 Serial.println("SPI intialization is complete");
 }

That isn't how you call a function.

It should read:

SPI_Init ();


Arduino Micro not providing regulated power I have an arduino micro that works fine off USB. I need to power it from an external 12V power supply. When I connect the 12V supply to the adjacent VIN and GND pins, the arduino will not power up. When I measure the power at VIN, it's 12V. When I measure power at the 5V pin, it's also 12V. If I disconnect the external power and go back to USB, it powers up.

Blown regulator?

In comparing this with another Arduino Micro, it appears that the regulator is malfunctioning.


How many stepper motors can a motor shield control? I have an application that calls for controlling two stepper motors. One motor does a constant speed scan, while the other would kick in at certain scanning positions of the first motor.

Can this be done with only one motor shield? The motors are relatively large, running on 12V.
Thank you!

There are motor shields that allow for running two stepper motors, like this one http://www.aliexpress.com/item/L293D-Motor-Drive-Shield-dual-for-arduino-Duemilanove-Motor-drive-expansion-board/32341780904.html?spm=2114.01010208.3.1.PA9IVu&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_10005_10006_10034_10021_507_10022_508_10020_10018_10019,searchweb201603_9&btsid=9d220772-7d0a-437d-8534-651a85644de4

Or there are boards that are smaller than a shield that you could use, like these:  http://www.aliexpress.com/item/28YBJ-48-DC-5V-Five-line-4-phases-Stepping-motor-Deceleration-stepper-motor-Fuses-length-25CM/818857514.html?spm=2114.01010208.3.1.LZ80QW&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_10005_10006_10034_10021_507_10022_508_10020_10018_10019,searchweb201603_9&btsid=201933bf-6385-4a45-a3c2-01236c01cd7a

But you will need to look at the specs to make sure they fit your needs, the best way to do that it to look at the main chip that is driving the motor and look at what that can do.

Hope that helps.


"Sharing" used GPIO pins I have a question regarding the ARDuino uno and some shields. I currently have a shield on my Uno, which takes the pins 0 to 7. However, on top of that board there is an extension of those 8 pins. If they were always in use, I suppose that the extra ports wouldn't be on top of the board, right?

Here's how it looks:

So it seems like you're able to "share" them. Is it possible to do so in real-time or is that there so you can use the ports when you disable the shield?

If its possible in real-time, how would I go about doing that? I've searched a little but couldn't find anything. I suppose i'd need some kind of clock to make the switch between the shield and the other components on pins 0-7, but not sure how to do that.

I'm kind of an electrics newbie, so hence the question might be a little silly :)

No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc).  General GPIO pins connect to just one device at a time.

I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use.  You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.

However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.


Is is possible to hook up an SD card and a GSM/GSRM module? Is it possible to hook up a GSM/GSRM module AND an SD card at the same time to an Arduino Uno, or any Arduino?

I want to build a cellphone to read off the buttons that are being dialed into it for a poor guy who has no hope of using a regular cellphone, and I figure I need to include wav files for the buttons (and any other functions) on an external source.

I'm a good programmer, so if I can hobble the parts together I can make them talk to each other.  But, I'm not so sure the different schemes for this all use the same pins, so I was wondering if someone would be so kind as to enlighten me..

Yes.

But let me try to talk you through it.

Step 1 - Analysis/Requirements:
Get your requirements right, what should your system do, what functionality.
So, GSM functionalities and SD card savings (in short).
One of the requirements would be that's it on an Arduino (atmega 328P).
Any other hardware requirements?

Step 2 - Design:
Check the possibilities with the Arduino, 1 hardware serial and multiple software serial connections. One hardware SPI/I2C I believe.
SD cards often use SPI connection and GSM units most likely use serial.
So this works great. Check some tutorials on SPI and (arduino) serial.

Step 3 - Wiring up
Wire everything up, as defined in the datasheet of the devices. Cross the Rx and Tx lines. Put MISO to MISO and MOSI to MOSI accordingly.
Be sure everything has enough power (GSM modules typically draw a lot of current when sending/connecting). Usually, if you find out that two devices are attached to the same pin, there might be something wrong (unless you can declare how they're seperated or why this is the case).

Step 4 - Implement
Well, you stated you're good at programming, so I'll leave this open for you.
But mind that it's only one of the three steps, so you should look at some tutorials, it'll learn a lot faster than asking everything. Try to get a bit comfortable with your thoughts, base them on things you have learned.

  So this shouldn't be an issue? Those pins aren't shared? - user1833028

Things like this can be found in the device's datasheet and if you follow some tutorials you'll see that they're different and why.

Also, what helps for me often, is to try to seperate this 'big' project into two smaller projects.
Try to get the GSM working and after that you go for the SD card reader.


L and ON keeps blinking I am not sure why the ON LED and the L LED keeps blinking on my Arduino.

I was just trying to implement a simple circuit using breadboard, and everything worked fine until I unplugged one wire with the power turned on. I accidentally made the wire touch something in the Arduino, and the LED in the breadboard became extremely bright. Then the ON LED and the L LED in the Arduino started to keep blinking, and I cannot download code to Arduino anymore. I am using IAR and IAR says AT91SAM3 reset: Communication breakdown after resetting target. Abort debug session?.

I think maybe there is a short cut when the wire touched the Arduino... But how can I determine what the problem is? Thank you very much, I am totally new to Arduino and has very limited knowledge about hardware...

You should split your problem in pieces. Like you cannot get communication with your Arduino again, so check first:

If you plug in the Arduino / USB, do you get a message on your computer?
Is it visible in the systems manager?
Is it visible by the IDE?
If you connect an adapter (12 or 9V), does it make a difference?
If you try another Arduino, does it work like it should be?

If you are a beginner, always make sure:

Never change any wiring with the Arduino on
Never have dangling wires, if you do not need a wire for the time being, either remove it completely or put it in a breadboard hole that is not used
Never change components with the Arduino on
After rewiring/adding/changing components, double check first

Update for comment below because it does not fit as comment:
To buy a cheap/fake (but working) Arduino uno, e.g.
Arduino Uno from Aliexpress


Strange compiler error (Segmentation Fault) You're getting a compiler error. It happens in strange parts of code that really shouldn't be having a problem.  The error looks something like:

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault

}

^

Please submit a full bug report,

with preprocessed source if appropriate.

See http://gcc.gnu.org/bugs.html for instructions.

lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status

compilation terminated.

c:/program files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed

collect2.exe: error: ld returned 1 exit status

What is it, and how do you fix it?

This is a known fault with the compiler in Windows.  The annoying thing is that it's the version of the compiler that is included in the Windows Store App version of the Arduino IDE.

It also snuck into the Windows version of the IDE from version 1.8.6 from the Arduino.cc website, with the bundled version of the Arduino AVR core.

There are numerous Github issues open for the problem and navigating the tangled web of them is a bit of a chore, but this one seems to be the most promising for digging into the root cause:

AVR core 1.6.22 (IDE 1.8.6) crashes avr-gcc compiler (5.4.0) when F() string is assigned to a static variable

The simplest fix is to downgrade your compiler to 4.9.2.  This can be done by using the Boards Manager to install version 1.6.21 of the Arduino AVR Boards.  This should give you compiler version 4.9.2-atmel3.5.4-arduino2 which doesn't suffer from the problem.


Does lowering arduino analog reference increase precision in measuring low voltage? The definition for Analog Reference is as follows: The reference voltage used for analog input (i.e. the value used as the top of the input range).

By default you have analog reference of 5V. So the precision of analogRead is 5 / 1023 = 0.0048875.

Now what happens if I lower the analog reference to let's say 1V. Does that mean that the precision now is 1 / 1023 (and the arduino can't measure voltages higher than 1V) or it is the same precision as before with the only difference being the fact that the arduino can't measure voltages higher than 1V anymore?

The former, i.e precision would now be 1/1023 but the accuracy of the AD converter is 4 / 1024 or 1 part in 256  i.e. 0.25%.

Also be aware that the internal reference voltages themselves are not very accurate :

DEFAULT: depends on your computer power supply USB2  Vbus = 4.4V - 5.25V, Vint 1 = 1.1V  actually 1.0 -- 1.2V, Vint 2 = 2.56V  actually 2.4 -- 2.8V


Delay versus polling power consumption? Does using the delay function use any less power than spinning in a polling loop on a timer?

That depends very much on how delay() was written (and how it will be written in the future!). There are "sleep modes", which will reduce the power consumption of the arduino - these are one of the best way to reduce power consumption. Delay() may or may not activate these. If not, there could be a replacement Delay() function that could do this.

If you want to reduce power, check out http://www.gammon.com.au/power - this is an excellent step-by-step tutorial on how to reduce power consumption from 50mA down to 288 µA