Can I use an internal clock on Wemos D1 Mini? I have a working Wemos D1 Mini setup measuring temperature and sending it over wifi to my server. Now I'm using a battery powered unit, and playing around with power consumption optimization and how to reduce it.
One thing I need is time (current, either epoch or DST) - so I implemented NTP, but everytime my ESP is waking up after deep-sleep, it needs to reconnect to wifi, gather time, measure temperature, send results.
This pdf states that ESP8266 has an internal clock. I'm having troubles finding anything beside "RTC shields on Wemos/Arduino" or "NTP on ESP8266" on the internet about something that is like an internal clock. There must be something, because otherwise it could not work (my understanding about clock and hardware is limited by now).
My question is: can I use NTP to update my internal clock, using it for some minutes (I think it will drift after some minutes), updating via NTP once in a while - to simply reduce network traffic and still use deep-sleep mode?
Any hints are welcome!

I think the answer to your question can best be summed up by one word: "Kinda".
The best reasoning is the NodeMCU Lua documentation which states:

Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, the RTC is not really a Real Time Clock in the normal sense of the word. While it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly between when the chip is running and when it is sleeping, meaning that any calibration performed while the chip is active becomes useless mere moments after the chip has gone to sleep. As such, calibration values need to be deduced across sleep cycles in order to enable accurate time keeping. [...]

So while it's called RTC it's not an RTC in the traditional sense - it's merely a timer that runs even when sleeping, but not with any degree of accuracy.
You can access the current RTC count with the Non OS SDK function
uint32_t system_get_rtc_time()

You can combine that with
uint32_t system_rtc_clock_cali_proc()

which gives you the number of uS per tick of the RTC timer.
There's no way to change the RTC timer count, so you will have to work out some "delta magic" to update your own internal time value (an epoch value is simplest) from the difference between successive calls to get the RTC count.
All somewhat tricky and the accuracy won't be great anyway, so you'll be wanting to use NTP to update that epoch value regularly.
But it could give you a "rough idea" of how long you've been asleep for, etc.
You would have to run some experiments to know how much the time drifts compared to the NTP value in real usage.


Arduino GSM Shield not responding? I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.

Would greatly appreciate it if someone can tell me where I could have gone wrong.

EDIT : I'm currently using the Arduino Mega. The shield I'm using is the Arduino GSM Shield. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see Sending a SMS message. Attached is what is shown on the monitor.

I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.

This is an old post, but for future people:

The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.


Servo Motor in function I have a project with 9 servo, I want to make a function to control each separate. Only that he is not accepting the servo as a parameter.
Can someone tell me if it is possible to pass the servant as a parameter, and how? Thank you!!
Example:

Servo s1,s2,s3;

void toMove(Servo obj,int inPosition, int forPosition){
var i = 0;
  for(i = inPosition; i<forPosition; i++){
    obj.write(i);
  }
}

void loop(){
  if(true){
     toMove(s1,0,180);
     toMove(s2,0,180);
  }
}

Yes, it is possible, and you've done it almost right. I made a minor correction in the toMove() function ("int" instead of "var"), and supplied the setup() function which you didn't show. It compiles without error. I didn't check it for correct operation as it looks like you had reduced your code to the minimum example necessary to demonstrate your question -- and thanks for that! Here is what I compiled:

#include <Servo.h>

#define SERVO1      9
#define SERVO2      10

/*****< External and Global Declarations >*****/
Servo s1, s2;
void toMove(Servo obj, int inPosition, int forPosition);

/*****< Local Function Prototypes >*****/

void toMove(Servo obj,int inPosition, int forPosition){
int i = 0;
  for(i = inPosition; i<forPosition; i++){
    obj.write(i);
  }
}

void setup()
{
    s1.attach(SERVO1);
    s2.attach(SERVO2);
}

void loop() {
   toMove(s1, 0, 180);
   toMove(s2, 0, 90);
}


Autoranging ohmmeter Note: Before i explain my issue i would like to note that I am a beginner in electronics. Please pay attention to that when providing solutions and explanations. Thank you.

I have succeeded at making an auto ranging Ohmmeter it is still ofcours experimental there for I would like to get some opinions and perhaps solutions to some of the issues I’m facing
How it works:

It is based on a simple voltage divider. After experimenting it seems that a voltage drop across the unknown resistor in a certain range (this case [3.135V, 0.99V] with a voltage source equal to 3.3V) gives the most precise results compared to other values.

This Ohmmeter has a very useful feature and that is auto ranging, it changes the range automatically when the voltage drop values are not in the previously mentioned interval ([3.135V, 0.99V]).
The accompanied image shows how the device works.

If the value of Rx is too small compared to (R1+R2+R3) the Arduino switches the analog reading from A0 to A1 if the problem still accurse the Arduino will change again to A2 meaning it is now measuring not the value of Rx but (Rx+R1+R2) in series after that the Arduino is programmed to do the subtraction accordingly.

This device presents some noticeable inconvenients  that need to be eliminated:

It depends on experimental values, so it is not certain if it’ll
function properly in different conditions.
For accurate (still not exact) measurements the value of Rx has to be greater than R1
It provides acceptable measurements compared to the actual value with an error that is not too big (less than 1% relative error) the precision was obtained by the use of some of the arduino functions (such as voltage reference) also I have chosen the voltage source to be 3.3V instead of 5V to reduce noise, now if one wishes to use a different microcontroller other than arduino will it still be possible to obtain the same precision.

I would like to know your professional opinion regarding these inconvenients and if you may solutions for them, I have accompanied the code for better understanding.

Thank you

#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analogPin0(A0, true);
ResponsiveAnalogRead analogPin1(A1, true);
ResponsiveAnalogRead analogPin2(A2, true);

int raw1= 0,raw2=0,raw3=0;
int Vin= 3.3;
float Vout1= 0,Vout2=0,Vout3=0;

float R1= 10000,R2=100000,R3=1000000;
float Rx= 0;
float buffer= 0;

void setup()
{
  analogReference(EXTERNAL);

Serial.begin(9600);
}

void loop()
{
  analogPin0.update();
  analogPin1.update();
  analogPin2.update();
raw1=analogPin0.getValue();
buffer= raw1 * Vin;
Vout1= (buffer)/1024.0;
if(Vout1<=3.135&&Vout1>=0.99) //firstif
{

buffer= (Vin/Vout1) -1;
Rx= (R1+R2+R3) * buffer;
Serial.print("Vout1: ");
Serial.println(Vout1);
Serial.print("Rx: ");
Serial.println(Rx);
delay(1000);
}
   else //else1 of first if
   {

   raw2=analogPin1.getValue();
   buffer= raw2 * Vin;
   Vout2= (buffer)/1024.0;
      if(Vout2<=3.135&&Vout2>=0.99) //second if of first else
      {
      buffer= (Vin/Vout2) -1;
      Rx= (R2+R3) * buffer;
      Rx=Rx-R1;
      Serial.print("Vout2: ");
      Serial.println(Vout2);
      Serial.print("Rx: ");
      Serial.println(Rx);
      delay(1000);
      }
      else
      {
      raw3=analogPin2.getValue();
      buffer= raw3 * Vin;
      Vout3= (buffer)/1024.0;
          if(Vout3<=3.135&&Vout3>=0.99)
          {
          buffer= (Vin/Vout3) -1;
          Rx= R3 * buffer;
          Rx=Rx-(R1+R2);
          Serial.print("Vout3: ");
          Serial.println(Vout3);
          Serial.print("Rx: ");
          Serial.println(Rx);
          delay(1000);
          }
       }
   }
}

======================================================

to jot here are the results as i have previously explained the ohmmeter worked pretty well at the beginning but when i turned it off Then back on the value measured changed, the error got much bigger i tried changing the caliber aka R1 from 220 to 100 but the results were the same, the error was still big
thank you

As you probably already know, the standard setup for measuring a
resistance with an Arduino is to put the unknown resistor in series with
a known one between 5V and GND, and measure the voltage at the point
in-between them:

     5V
     │
     R₁
 A0 ─┤
     R
     │
    GND

where R is the unknown resistor and R1 is the known
reference. The resistance is then computed as:

const float R1 = ...;  // reference resistance

int reading = analogRead(A0);
float R = (float) reading / (1024 - reading) * R1;

First, it is worth noting that the reference voltage does not appear in
this calculation. You could, of course, do the calculation in terms of
voltage, but you should then notice that the reference voltage can be
simplified away. This is not surprising if you realize than the ADC of
the Arduino does not actually measure a voltage: it rather measures a
voltage ratio: the ratio of the input voltage to the reference
voltage. This ratio can then be easily related to the resistance ratio
R/R1. What all this implies is that you should not expect to
get better accuracy by using a 3.3 V reference rather than
5 V. Any inaccuracy in the voltage reference is irrelevant to the
measurement of the resistance.

Next, when measuring a physical quantity, you are almost always
interested in the relative rather than the absolute accuracy. From
the equation above, it can be easily shown that you get the best
relative resolution when the reading is near the middle of the ADC
range:

raw reading    │   64 │  128 │  256 │  512 │  768 │  896 │  960
───────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────
resolution (%) │ 1.67 │ 0.89 │ 0.52 │ 0.39 │ 0.52 │ 0.89 │ 1.67

This is consistent with your observations, and it means that the
reference resistor should ideally have a value that is of the same order
as the unknown resistor.

Now, for the autoranging, I would advise you against putting all your
reference resistors in series. With this setup, you always have the same
voltage across the unknown resistor, irrespective of what range you
choose. Reading a different input does not help. You may find out that
the voltage between R1 and R2 gives a better
reading (closer to mid-range), and you get a better accuracy on the
measurement of R+R1. However, when you subtract R1
you are immediately degrade the relative accuracy of the result. In
the end you cannot really improve the accuracy this way.

What I suggest is to put the reference resistors in parallel instead of
in series, and power each one from an analog pin:

     A1  A2  A3
     │   │   │
     R₁  R₂  R₃
 A0 ─┼───┴───┴── ...
     R
     │
    GND

You then use these analog pins in digital mode: all of then in INPUT
mode, except one which is set to OUTPUT HIGH. You can try all of
them in turn and select whichever gives a result closer to mid-range. Or
you can implement a smarter algorithm that finds the optimal one without
trying them all.

There is something to be aware of with this setup: the pins have an
output resistance that is about 25 Ω, which ends up being in series
with the corresponding reference resistors. You can account for that by
adjusting, in your code, the values of those references. But then that
output resistance is not very well known, and can vary with temperature.
This should only be an issue when you are in the low ranges though. You
can mitigate this problem by measuring the voltage at the pin that is
currently pulling up, and replacing 1024 in the equation for R by that
reading. That's why I suggest to use analog instead of digital pins.

Finally, there are a couple of limitations that you should be aware of
when measuring resistances with the Arduino ADC. At the low end of the
resistance range, you cannot use a reference resistor with a very low
value, because you have to make sure you do not pull more than about
20 mA from the pin that pulls up. Your smallest reference may then
end up being somewhere around 220 Ω, and you will loose significant
accuracy when you try to measure anything below 50 Ω. At the upper
end of the range, you should be aware that the ADC is meant to measure
voltage sources with an output resistance no larger than 10 kΩ,
otherwise you risk cross-talk between the ADC channels. Then your higher
reference should probably be 10 kΩ, and any measurement above
50 kΩ will give poor accuracy. Going past these limitations would
require extra electronics, like a good-quality op-amp to “condition” the
signal into something that the ADC can reliably measure.


My Arduino Ethernet shield is not working Actually I'm using a W5100 Hanrun HR911105A 16/02 Ethernet shield with an Arduino Uno (original).

I tried this code from the examples:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean gotAMessage = false;
// whether or not you got a message from the client yet

void setup() {
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // start the Ethernet connection:
  Serial.println("Trying to get an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // initialize the Ethernet device not using DHCP:
    Ethernet.begin(mac, ip, myDns, gateway, subnet);
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  ip = Ethernet.localIP();
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(ip[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
  // start listening for clients
  server.begin();
}

void loop() {
  // wait for a new client:
  EthernetClient client = server.available();
  // when the client sends the first byte, say hello:
  if (client) {
    if (!gotAMessage) {
      Serial.println("We have a new client");
      client.println("Hello, client!");
      gotAMessage = true;
    }
    // read the bytes incoming from the client:
    char thisChar = client.read();
    // echo the bytes back to the client:
    server.write(thisChar);
    // echo the bytes to the server as well:
    Serial.print(thisChar);
    Ethernet.maintain();
  }
}

That code prints the following on the serial monitor:

Trying to get an IP address using DHCP
Failed to configure Ethernet using DHCP
My IP address: 192.168.1.177.

So what is the problem? Why it is not connecting? I tried all the ethernet examples, but not one works. I don't know, maybe the problem is that I don't have a sticker of MAC address on the shield and I'm using the MAC address of the examples. Or maybe I'm writing the IP address wrong? Here is the data from the network connection details.

Connection-specific DNS Suffix: zte.com.cn
Description: Intel(R) Dual Band Wireless-AC 3165
Physical Address: 72-57-C5-BC-66-07
DHCP Enabled: Yes
IPv4 Address: 192.168.1.2
IPv4 Subnet Mask: 255.255.255.0
IPv4 Default Gateway: 192.168.1.1
IPv4 DHCP Server: 192.168.1.1
IPv4 DNS Server: 192.168.1.1
IPv4 WINS Server:
NetBIOS over Tcpip Enabled: Yes
Link-local IPv6 Address: fe80::b523:b9f2:b43c:6a8a%14
IPv6 Default Gateway:
IPv6 DNS Server:

My router is a ZTE model ZXHNH108N.

If your Arduino can not get an IP address, it could be because there is a problem with your code, your shield or your network.

There doesn't seem to be a problem with your code from a quick glance, so let's look at the network.

The cable. Are you using the right sort of cable? You should be using a Cat5e straight through cable. Cat5e is the type of cable for Ethernet, if it is plugged into the router and you didn't make it yourself, it is probably either a CAT5e or CAT6 cable, so it will be OK. There are two types of cable and they are almost impossible to tell apart, the normal sort is a "straight through" cable, which means the Transmit and Receive pins at one end go to the Transmit and Receive pins at the other end. The other sort is a "crossed" cable where the Transmit goes to the Receive, this is for connecting a computer to a computer.  Since you are plugging to a router you should have a straight cable, if in doubt test it with a working device, ie plug it into your PC.
DHCP - I see from your PC output DHCP is enabled on 192.168.1.1 and I guess this is your router. A DHCP server needs to know what addresses it can give out to devices, these addresses are called "the DHCP pool". If you have no more free addresses in the pool then you can't connect anymore devices. It sounds like you haven't restricted your pool, but it might be worth logging onto your router and seeing if you can see what addresses are in the pool or range.
MAC Filtering - For security some routers only allow certain MAC addresses to connect to the router and request a DHCP address. If you have it turned on then add your MAC address to the white list. If you don't have it turned on, don't worry.
Speed - I suspect that your shield has a maximum speed of 10MBs. Most modern networking equipment only supports 100/1000MBs so the shield just won't work with your router. Your router should have the numbers near the wired sockets to confirm or deny this.

If none of that works the you are going to need to see if you can read the data from the shield and see if you can work out what is going wrong. You will need a network snooper like WireShark and a HUB. An Ethernet switch will not work, it must be an Ethernet Hub, because switches don't rebroadcast the data on all ports. If your PC has two network cards you could set it up as a 'bridge' and you can snoop on the data as it passes across the bridge.

Sorry if some of these terms are confusing, but you should be able to Google them and get a better explanation than I can give you in the space here.

One final thought: are you running the Arduino from a battery? If so it might be worth using a mains supply, because the battery might not be able to support the Ethernet transmissions.


How can I find and specify the address of my adafruit MMA8451 accelerometer in arduino code? I am trying to use four of the same accelerometer on the same bus and acquire data from each of them using an SD card. Because I am using four of the same accelerometer I need to be able to differentiate between them and I dont know how to find their specific address. I need the specific address so I can tell my arduino which accelerometer to pull data from. essentially it would pull data from 1 then 2 then 3 then 4 and loop back to 1.

You can't have 4 of those on one bus. The maximum is 2.

The pin SA0 defines the least significant bit of the I2C address. From the datasheet:

  7 | SA0 | I2C least significant bit of the device I2C address, I2C 7-bit address = 0x1C (SA0 = 0), 0x1D (SA0 = 1).

In fact, as it states on the Adafruit website (if you'd care to read it sometime):

  A is the I2C Address select pin. By default this is pulled down to ground with a 10K resistor, for an I2C address of 0x1C. You can also connect it to the 3Vo pin for an address of 0x1D

If you want more than 2 you will either have to have multiple I2C busses or use an I2C multiplexer (such as this one) to select different branches on the same bus.


Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running Atmel Studio.

Thanks!

EDIT:  Sorry for double posting, I posted in electronics before I noticed there was an Arduino specific section.

If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose Burn Bootloader from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


Bad Data : Arduino Mega & NodeMCU Serial Communication Currently I am working on an Arduino project. The project required to establish communication between Arduino Mega and NodeMCU ESP8266. Here are some details about the project:

NodeMCU Rx Pin is connected to Arduino Mega Pin 14 (Tx3), while NodeMCU Tx Pin is connected to Arduino Mega Pin 15 (Rx3), Jumper Wires is used to connect NodeMCU and Arduino Mega
Both Arduino Mega and NodeMCU are using baud rate 115200

Code for NodeMCU ESP8266 (Send The Data to Arduino Mega):

void loop(){
       esp.println("0000");

       esp.flush();
}

Code for Arduino Mega (Receive Data) :

 if(Serial3.available()){

  data = Serial3.readStringUntil('\n');

  Serial3.flush();

  Serial.println(data);

}

The result :

The intented and expected result is "0000", however, the result shown in serial monitor is not accurate. Anyone could advise?

Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


Using millis() function to start at potentiometer reading I am trying to use the millis() function to start a countdown of 3 seconds when I turn my potentiometer to high travel. My code so far starts the timer at the beginning of the loop or when reset is hit or when the sketch is uploaded to the board. I need the countdown to start when the potentiometer reaches high travel.

The goal of the program is that when the potentiometer reaches high travel, PumpOne starts (HIGH) and if the potentiometer does not reach low travel before 3 seconds, PumpTwo will come on (HIGH). I am trying to simulate a water tank with two pumps (LEDs in this case) and the potentiometer high and low travel representing the high and low levels of the tank respectively.

I've updated the code since the original post but the timer still starts from the beginning of the program and not when L > Plim1.

Here's the code:

int Pump1 = 3; // Declare Blue LED in pin 3 to simulate Pump 1
int Pump2 = 4; // Declare Green LED in pin 4 to simulate Pump 2
int Alarm = 2; //Delcare Red LED in pin 2 to simulate Alarm
int TDCRPot = A0; // Declare Potentiometer(TDCRPot) an int and assign to pin A0

int L; //Declare L a variable to read the High and Low
//travel of the potentiometer

float Plim1 = 1000; // pot reading for pump 1 turn on
float Plim2 = 1000; // pot reading for pump 2 turn on
float Llim = 100; //pot reading to turn both pumps off
unsigned long T; // current time
unsigned long T1 = 0; // P1  on time
boolean P1 = false;
boolean P2 = false;
boolean Alarmstate = false;
unsigned long Tlim = 3000;

void setup() {
  Serial.begin(9600); //Turn on Serial monitor for troubleshooting
  //purposes and set to 9600 baud
  pinMode(Pump1, OUTPUT); //Declare Blue LED(PumpOne) an output
  pinMode(Pump2, OUTPUT); //Declare Green LED(PumpTwo) an output
  pinMode(Alarm, OUTPUT); //Declare Red LED(Alarm) an output
  pinMode(TDCRPot, INPUT); //Declare Potentiometer(TDCRPot) an input
}

void loop() {
  L = analogRead(TDCRPot); //Read the voltage from the Potentiometer pin
  if (!P1 && L > Plim1) {
    T = millis();
    digitalWrite(Pump1, !P1);
  }
  if (Pump1 != P1 && T - T1 > Tlim && L > Plim2) {
    digitalWrite(Pump2, !P2);
  }
  if (Pump1 != P1 && L < Llim ) {
    digitalWrite(Pump1, P1);
    digitalWrite(Pump2, P2);
  }
}

The statement TDCRLevel = analogRead(TDCRPot); will almost always set TDCRLevel to a non-zero value; hence the && TDCRLevel term of your last if statement almost always is satisfied.  The only time it won't be satisfied is when TDCRLevel is exactly zero.

When TDCRLevel >= 1000 is first satisfied, it's likely to be true for some while; during that time, each pass through loop() will toggle Bluestate and set previousMillisBlue = currentMillis.  This happens many times per millisecond while TDCRLevel has a high value.  Whether Bluestate is on or off when  TDCRLevel goes below 1000 is a fairly random outcome.

To handle the process properly, set up a state machine, using either one state-number variable or several variables to maintain state.  Change states when conditions tied to state, TDCRLevel, and time are met.

More simply, something like the following might work.

loop:
  if !P1 and L > Plim1:
    Set P1; record T1
  if P1 and T-T1 > Tlim and L > Plim2:
    Set P2
  if (P1 or P2) and L < Llim:
    Turn off pumps, clear P1 and P2

where P1, P2 represent pump states; T represents current time and T1 represents time that P1 most recently turned on; L = analogRead(TDCRPot); Plim1 and 2 are pot levels for pump turnons; Llim = low level for pump turnoffs; Tlim = desired time delay before pump 2 comes on.

Edit 1:  The above is pseudocode, rather than any simulacrum of valid C or C++.  As such, you may need to add sets of parentheses and brackets, substitute meaningful variable names, etc.

Note that the constants Plim1, Plim2, Tlim, Llim should be declared via either const int declarations, or via enum {} constructs (enum declares only integer constants), if they are integers rather than floats.  For example, do like either of

const int Plim1 = 1000; // level for pump1 turnon
const int Plim2 = 1000; // level for pump2 turnon
//etc

or

enum { Plim1=1000, Plim2=1000, Tlim=3000, Llim=100};

The phrase “Set P1; record T1” corresponds to code like

P1 = true;
digitalWrite(Pump1, HIGH);
T1 = millis();

in braces.  If you don't set P1 and record T1 as current time, the process won't work.  P1 and P2 represent state variables, not constants.

The phrase “if P1 and T-T1 > Tlim and L > Plim2: Set P2” corresponds to code like

if (P1 && (T - T1 > Tlim) && (L > Plim2)) {
  P2 = true;
  digitalWrite(Pump2, HIGH);
}

The phrase “if (P1 or P2) and L < Llim: Turn off pumps, clear P1 and P2” corresponds to code like

if((P1 || P2) && (L < Llim)) {
  P1 = P2 = false;
  digitalWrite(Pump1, LOW);
  digitalWrite(Pump2, LOW);
}


How do I split an incoming string? I am sending a list of servo positions via the serial connection to the arduino in the following format

1:90&2:80&3:180

Which would be parsed as:

servoId : Position & servoId : Position & servoId : Position

How would I split these values up, and convert them to an integer?

Contrarily to other answers, I'd rather stay away from String for the following reasons:

dynamic memory usage (that may quickly lead to heap fragmentation and memory exhaustion)
quite slow due to construction/destruction/assignment operators

In an embedded environment like Arduino (even for a Mega that has more SRAM), I'd rather use standard C functions:

strchr(): search for a character in a C string (i.e. char *)
strtok(): splits a C string into substrings, based on a separator character
atoi(): converts a C string to an int

That would lead to the following code sample:

// Calculate based on max input size expected for one command
#define INPUT_SIZE 30
...

// Get next command from Serial (add 1 for final 0)
char input[INPUT_SIZE + 1];
byte size = Serial.readBytes(input, INPUT_SIZE);
// Add the final 0 to end the C string
input[size] = 0;

// Read each command pair
char* command = strtok(input, "&");
while (command != 0)
{
    // Split the command in two values
    char* separator = strchr(command, ':');
    if (separator != 0)
    {
        // Actually split the string in 2: replace ':' with 0
        *separator = 0;
        int servoId = atoi(command);
        ++separator;
        int position = atoi(separator);

        // Do something with servoId and position
    }
    // Find the next command in input string
    command = strtok(0, "&");
}

The advantage here is that no dynamic memory allocation takes place; you can even declare input as a local variable inside a function that would read the commands and execute them; once the function is returned the size occupied by input (in the stack) is recovered.


Is the used clock for the Baudrate generator adjustable on an arduino due? I hope to find some answers or pointers to a boggling task of mine:

Having an Arduino DUE that I want to push to its serial limits, I came up with the idea of hooking it up to my rPi via serial at least at 921600 baud.

Technically both seem capable of that. A loopback test with the rPi was successful up to 921600 and I've managed to get a "good" quality transmission up to 576000 bps already (error-rate should be around 1,3%), but anything higher gets problematic.

Problems:

DebugConsole, CuteCom and minicom don't have support for any speeds in-between, so either 921600 works or it doesn't
minicom supports 1.000.000 baud, but this would still mean a ~5% error-rate, which is according to my calculations and tests, but they are in question here as well ...

From the Atmel Doc I've got

BaudRate = MCK ⁄ CD × 16

From that I've derived that with the 84MHz Due a baudrate of 1.050.000 would be the actual rate I should aim for, as CD must(?) be an INT.

1050000 = 84000000 / 5 * 16

Questions:

Is my assumption of an optimal 1.050.000 baudrate right?
Is it possible to use a different clock for the baudrate generator than the 84MHz?

Remarks:

A Clock of 14,7456MHz should be optimal as it is equal to 921600 * 16.

I am using TXD/RXD1 on the Due.

The Due is transmitting on 921600 but the data is scrambled due to the errors.

In case somebody is wondering, my hope is that it is easier to adjust the arduino to 921600 baud than it is to setup a tool and configure the rPi to support 1050000 baud - but I am working both ways, only that with the rPi I know what to do ..

The clock of the transmitter and receiver have to be matched.

In theory, the worst case error tolerable is 1/2 bit per byte.  For the 10 bit byte (1 start, 8 data, 1 stop) that leads to a +/- 5% clock error tolerance that you will find reported.  Note that this actually depends on the specific UART implementation, either chip or internal.  There are various methods of sampling that make some UART's better than others.  It is common to sample in the middle, but some chips have methods to improve noise rejection.

For the receiver side, do not rely on what the terminal program is showing you.  Few applications would manipulate the clock directly; they commonly just call an API with an enumerator for the speed.  You need to know exactly what hardware the receiver side has and its clock.

In practice, the theoretical limit is not going to work.  At high data rates, the noise on the cable will eat away at that safe margin.  More common recommendations will say +/- 1% which allows for noise on the edges of the bit transitions.

The noise on the signal is important at these data rates.  You indicate you are using TXD/RXD which is just logic level.  You cannot connect logic level any significant distance.  If the two are directly next to each other with excellent attention to wiring, you might have a chance.  Adding transceivers will help your chances significantly.

Also, note that changing to 7 bits helps.  Do you need 8 bit data?

So in summary:
- The receiver is more important than the transmitter, but they both have to match.  If you can't find a match of clocks to 1%, you will have data errors.
- At these speeds, the cabling and connection is critical.

This article at Maxim is a good starter Maxim "Determining Clock Accuracy Requirements for UART Communications.


ESP8266-01E is not responding after successful flash I have flashed an ESP8266 with the ESP8266 flash downloader that said my flashing had succeeded.
But when I sent an AT command from the serial monitor it didn't respond and the TX/RX LED from the ESP8266 didn't respond either. I checked all baudrates from 300-200000, but nothing.
I was using CH340 USB to TTL for flashing wired like this:
USB -> ESP8266
3,3v ->CH_PD and VCC
GND -> GND and GPI0 (only when flashing)
TX -> RX
RX -> TX

I was flashing to downgrade the firmware; the default firmware from shop was SDK 1.5.4, AT VERSION 1.1.0.0.

I have been frustrated with this, because this is my second module.

SOLVED
My module is esp8266-01S, i need to set the SPI MODE to DOUT, BAUDRATES=115200, SPI SPEED 40MHz and the software is NODEMCU FLASHER.
The important keyword is "DOUT".
I have been flash many times but with not DOUT SPI METHOD. I thought change it will not fix that. I was using QIO SPI MODE but it doesn't work.


Play .Wav sound only once on switch change I have a project where if you change the value of the spdt switch the colour of the LEDs change. As well as this a .wav file plays. The problem is I only want the .wav to play once. At the moment it constantly plays over and over as it's within the loop. I've tried using a mute or disabling the pin after the play through but I am unable to re-enable so I scrapped it. I deally I want to keep the SPDT switch due to asthetics instead of a push switch. This is my code:

#include <TMRpcm.h>
#include <SD.h>
#define SD_ChipSelectPin 10
#include <SPI.h>

TMRpcm tmrpcm;

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

tmrpcm.speakerPin=9;
Serial.begin(9600);
if(!SD.begin(SD_ChipSelectPin))
{
  Serial.println("SD fail");
  return;
}
     tmrpcm.setVolume(6);
     tmrpcm.play("1.wav");
     while (tmrpcm.isPlaying()) {
     delay(1);
}
     tmrpcm.setVolume(6);
     tmrpcm.play("3.wav");
//set the switch input, pin 8, as an
pinMode(8, INPUT);

//set both the LED pins, pin 5 and 6 as OUTPUTs
pinMode (5, OUTPUT);
pinMode (6, OUTPUT);
 delay(1000);
}

void loop()
{
 int switchValue = digitalRead(8);
 if (switchValue == 1)
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
  tmrpcm.setVolume(6);
  tmrpcm.play("4.wav");
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);

}
else
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
   digitalWrite(6,HIGH);
   digitalWrite(5,LOW);
   tmrpcm.setVolume(6);
   tmrpcm.play("5.wav");

}
}

how can I make the wav play once but when the switch changes?

Make a variable to hold the "last state" of the switch. Compare that last state to the current state as obtained by switchValue = digitalRead(8).

Only call the play function if the old value and the current value are different.


Can I connect an Arduino GSM Shield directly to a PC? Is it possible to communicate with and use the GSM shield directly from the computer, without using an arduino board?

You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

  Power
  It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.


Calculate the time since arduino started working for a year I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on

The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.

It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.

Are you a good software engineer ? How can you be sure that it will work ?


How to transfer data from arduino to android via bluetooth? I am having arduino uno board connected with bluetooth HC-05 module. I needed to transfer the data from arduino to android mobile via bluetooth.

Is it possible to transfer the data from arduino to android via bluetooth?

Is it possible to transfer the data from arduino to android via bluetooth?

Yes.  The HC-05 just creates a serial connection over bluetooth.  You can treat it just like any other serial connection, such as the USB connection between the Arduino and your computer.

What data you send and in what format you send it is entirely up to you.


Arduino disecting a string Hello I have a String that contains the following: "println('hello world')".
I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.

    String line1 = "println('hello world')";

Please help me thx.

How can I remove everything except for what is in the brackets from the string?

There are a number of String class member functions that can help with this. First, indexOf(val) will help locate the character of interest. Second, substring() will help cut out the part you want. And as a bonus, using lastIndexOf() will allow brackets within the string.

String s = "println('hello world')";
s = s.substring(s.indexOf('(') + 1);
s = s.substring(0, s.lastIndexOf(')'));

Cheers!


EEPROM value reverting to 255 When I write '13' to the EEPROM and read it straight after it works correctly.

However when I comment out the write part of the code and try to just read the data, the value is no longer 13 as it used to be but reverts back to 255. Whats going on?

I am running a standalone atmega328 on a breadboard with a 16mhz crystal, programmed by a Nano R3.

void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);

//EEPROM.write(1,13);
}

void loop() {
scoreBinary();

}

void scoreBinary(){

int score= EEPROM.read(1);

if(score==13){
digitalWrite(2,HIGH);
}
delay(10000);
}

By default the EEPROM in the MCU is erased (to 0xff) when the chip is erased before flash is written to. If you want to prevent this then you will need to program EESAVE in the fuse bits, which is bit 3 in the high fuse byte of the '328.


smoke came out of Arduino Nano I was working with Arduino and Xbee with LED, circuit LED  + Servomotor
and doing testing for 5 hours (not continuously).

Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side).  I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.

Is there any chance to fix the board?

I discovered that the B2 diode cracked in the middle, the picture is showing a  good Arduino Nano.

I found a very similar in this post about dead NANO

If my understanding is correct, the flex sensor was connected between 5V and GND.
This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.

Supposing you have an genuine arduino UNO, here is a schematic but it may not be the right version

Remove the MCU
Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

EDIT for Arduino Nano

I did not understand you had a nano board (schematic)

The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.

If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)


how do i know what battery(how much ampere and voltage) my circuit needs to work perfectly? i really love to make a lot of things  but i always have this problem that i don't know how can i determine what battery(with how much voltage and amp)my circuit must have to work perfectly! please help me:( for example i have two circuits.circuit 1  includes:arduino uno ,2 servo motors and a DFplayer module and an led but i don't know is a 7.4 voltage Lipo battery with 1500mAh suitable for it or not???
and circuit 2 includes:arduino uno,L298 driver & 2 dc motors & 2 ultrasonics sensor but i don't know what battery does it need?
i really love to learn it (determine the battery  my self)

TL;DR: You really need to know what components you have and you need to find datasheets. In the datasheet, you find what voltage the component requires.

Don't care too much about amperes in the beginning. If you get the voltage right, each component will just draw as much current as it needs.

An Arduino Uno operates from 7 to 12 Volts, so 7.4 V is ok.

"Servo motor" is simply not enough information. There are servo motors for 4.8 V, some for 6 V and others for 12 V. There are even AC servo motors for 240 V~.

DFPlayer is for 3.2 V to 5 V, so it shouldn't be powered directly off the 7.4 V battery. Maybe it can be powered from a 5 V pin of the Arduino. Since they power it from the 5 V pin, it seems to be possible.

Also "LED" is not a term that is good enough. Is it Infrared, Red, Yellow, Green, Violet, UV or white? Depending on the color, it needs something between 1.6 and 3.0 V. Therefore, you need a resistor. What's the use of the LED? Do you need to turn it on and off by Arduino, or can it just be always on from the Lipo battery?

The L298N has a supply voltage from 2.5 V to 46 V, so 7.4 V is fine.

Next, "DC motor" is not specific enough. I have seen 3 V, 5 V, 6 V, 12 V, 24 V.

Also, for ultrasonic, there are SR04 and SRF05. These two operate at 5 V. But if you have a different one, that may not be the case.


Using micros() to measure analogRead() time varies based on Serial.print location? I'm trying to use micros() to measure the time it takes to execute an analogRead() cycle, but am having some issues.  Originally, I just printed out the measured time for the analogRead() right after doing the subtraction, but I wanted to change that to printing out all of the time values for the 100 loops at once.  When I print the start times, end times, and values both in the if statement (right after calculating them) and at the end, the values printed are the same.  I'm not sure if they're accurate because they fluctuate a lot within those 100 tests.  For example, some of these measured times consecutively are 216, 97, 153, 34, 89, 145, 27.  I put the ADC in freerun mode, so I figured it could be normal for that.  However, when I don't print the start times, end times, or values immediately after calculating them and instead try to print them in the else if statement, it gives a stream of values that are all either 407 or 408.  If I print "Test" instead of the values right after calculating them, it still gives the (I'm assuming) correct values that vary a lot, not the 407s.  If, instead of printing them in the if statement, I print them just in the general loop (currently commented out) and the else if statement, they are still the varying maybe-correct values.  I assumed that even if the values aren't being printed, they're still being stored in the array correctly.  I don't understand why printing something unrelated right after storing the values would change them.  Any ideas?

Thanks

    int sensorPin = A1;    // select the input pin for the potentiometer
    int ledPin = 13;      // select the pin for the LED
    int sensorValue[1000];  // variable to store the value coming from the sensor
    int ind = 0;
    int starts[1000];
    int ends[1000];
    int vals[1000];
    int stopprint = 0;
    int i = 0;
    int countto = 100;

    void setup() {
      // declare the ledPin as an OUTPUT:
      Serial.begin(57600);
      analogReadResolution(12);
      pinMode(ledPin, OUTPUT);
      Serial.println("ready to begin");
        analogReadSetup(A1);
      for (i = 0; i < 1000; i++) {
        starts[i] = 0;
        ends[i] = 0;
        vals[i] = 0;
      }
    }

    void loop() {
      // read the value from the sensor:
      if (ind < countto) {
      starts[ind] = micros();
    //  delay(50);
      sensorValue[ind] = analogRead(sensorPin);
      ends[ind] = micros();
      vals[ind] = ends[ind] - starts[ind];
    //  Serial.println("Test");
        Serial.print(ind);
        Serial.print('\t');
        Serial.print(starts[ind]);
        Serial.print('\t');
        Serial.print(ends[ind]);
        Serial.print('\t');
        Serial.print(vals[ind]);
        Serial.print('\t');
        Serial.print('|');
        Serial.print('\t');
      Serial.print('\n');
      Serial.print('\r');
      ind++;
      }
      else if (stopprint == 0) {
        Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
        for (int j = 0; j < countto; j++) {
    //        Serial.println(j);
            Serial.print(starts[j]);
            Serial.print('\t');
            Serial.print(ends[j]);
            Serial.print('\t');
            Serial.print(vals[j]);
            Serial.print('\n');
            Serial.print('\r');
            stopprint = 1;
        }
      }
      else if (stopprint == 1) {
        while(1);
      }
    //  Serial.print(ind-1);
    //  Serial.print('\t');
    //  Serial.print(starts[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(ends[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(vals[ind-1]);
    //  Serial.print('\n');
    //  Serial.print('\r');
   }

Also, I'm using the Arduino Zero if it makes a difference.

Not sure if it is related to your problem but... if I were to try such a
measurement, I would use local variables, like

unsigned int start = micros();
int value = analogRead(sensorPin);
unsigned int end = micros();
sensorValue[ind] = value;
starts[ind] = start;
ends[ind] = end;
vals[ind] = end - start;

This way you would be measuring the time it takes to call both
analogRead() and micros(), and very little more. If you do something
like

sensorValue[ind] = analogRead(sensorPin);

then you are also measuring the time taken by the pointer arithmetic and
the memory access.

I generally program AVR-based Arduinos. These have a load-store
architecture, where saving to a local variable costs essentially
nothing, as the variable is typically assigned a CPU register by the
compiler. Saving to a global takes more time because of the RAM access.

I have no experience with ARM-based Arduinos, like the Zero, but I
believe it's also a load-store architecture, thus the same
considerations should probably apply.

Update: I tried the following experiment on my Uno:

#define PRINT_WHILE_READING

#define READ_COUNT 100

void setup() {
    unsigned int starts[READ_COUNT];
    unsigned int ends[READ_COUNT];
    unsigned int vals[READ_COUNT];

    Serial.begin(57600);
    Serial.println("Ready to begin");

    // Take the readings.
    for (int i = 0; i < READ_COUNT; i++) {
        starts[i] = micros();
        analogRead(A1);
        ends[i] = micros();
        vals[i] = ends[i] - starts[i];
#if defined(PRINT_WHILE_READING)
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
#endif
    }

#if !defined(PRINT_WHILE_READING)
    // Print them now.
    Serial.println("All data taken");
    for (int i = 0; i < READ_COUNT; i++) {
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
    }
#endif
}

void loop() {}

If PRINT_WHILE_READING is defined as above, I get times that fluctuate
between 108 and 116 µs. If I comment out the line
#define PRINT_WHILE_READING, I get mostly 116 µs and,
occasionally, 124 µs. In both cases, the first reading takes longer
(208 and 212 µs respectively).

The fact that the first reading takes longer is explained in the
datasheet: the ADC does some initializations in that first reading. All
measured times are multiples of 4 µs because that is the resolution
of micros().

Now, trying to understand the differences between the two cases:

With PRINT_WHILE_READING the times are shorter on average. This is
because the numbers are not stored in RAM, as the compiler figured
out the arrays starts[], ends[] and vals[] are not really
needed and optimized them away. When PRINT_WHILE_READING is not
defined, I can see the “store in RAM” instructions in the generated
assembly.
With PRINT_WHILE_READING the numbers fluctuate more. I guess this
is due to the printing through the serial port taking a variable
amount of time depending on the numbers being printed, and thus
creating timing inconsistencies.

The last point deserves some explanation. The ADC is clocked by a
prescaler that divides the frequency of the main clock by 128. This
gives a clock period of 8 µs. When an ADC conversion is started,
the ADC waits for the next rising edge of its clock, which can take
anywhere between 0 and 8 µs, then it does the conversion in
13 cycles of its clock. This means the whole process can take
anywhere between 104 and 112 µs depending on the exact time the
conversion is started relative to the phase of the prescaler. If the
conversions are started at irregular intervals, you expect to see
roughly 8 µs of fluctuation in the measured times.

All these observations have been done on an Uno, which is based on an
AVR clocked at 16 MHz. I know the Zero is quite different. You will
have to look at the datasheet of the ATSAMD21G18 to see whether anything
of the above can be extrapolated to the Zero.


I2C wire.h send 2 variables I am trying to send 2 variables with wire.h. I tried with  this code:

MASTER RECEIVER:

#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;
char t[10] = {};
char v[10] = {};

void setup() {
  Wire.begin(); // join i2c bus with address #4
  lcd.begin(16, 2);
  Serial.begin(9600); // start serial for output
  //-----------orologio-----------
  RTC.begin();
  // Check to see if the RTC is keeping time. If it is, load the time from your computer.
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------
}

void loop() {
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Wire.requestFrom(8, 6);
  int i = 0;
  while (Wire.available()) {
    Serial.println(i);
    t[i] = Wire.read();
    // every character that arrives it put in order in the empty array "t"
    i = i + 1;
  }
  Serial.println(t);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = (annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(t);
  lcd.setCursor(5,0);
  lcd.print(v);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);
  delay (1000);
  lcd.clear();
}

SLAVE SENDER

#include <Wire.h> // si include la libreria
//---------------------------------------------------------
char t[10];
char v[10];

void setup() {
  Wire.begin(8);
  // join i2c bus (address optional for master)
  Wire.onRequest(requestEvent);
}

void loop() {
  int mioInt = random(30000);
  int mioInt2 = 1234;
  dtostrf(mioInt, 3, 2, t);
  //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  dtostrf(mioInt2, 3, 2, v);
  //------------------------------------------------------
  delay (500);
}

void requestEvent() {
  Wire.write(t);
  Wire.write(v);
}

I'm unable to receive v in my master receiver. Thanks for your help.

I2C is 8-bit data bus, where address can be 7 bit or 10 bit, you can't send more than 8 bit at a time, if you want to send data more than 8 bit you will be sending them like this, for example let you need to send 16 bit data then you send 8 bit LSB first and then 8 bit MSB or vice versa as per your configuration.

Secondly I had noticed you code and noticed many errors, the major one is that you hadn't followed the rules of I2C protocol in your code. I am here attached a link for sample program of arduino i2c slave and master. Go through it you will get your answer.


How to calculate air velocity from wire resistance? I want to construct a constant current hot wire anemometer. For this, resistance is the input of the Arduino. There is a relationship between wire resistance and air velocity.

How can I calculate velocity from wire resistance?

Its very simple really, all you need to do is code the equations on this page and then supply some heat and you will be able to do it.  Just remember integer division rounds down :)

http://www-g.eng.cam.ac.uk/whittle/current-research/hph/hot-wire/hot-wire.html


Is this bluetooth setup good? I am trying to do this tutorial http://www.instructables.com/id/Chappie-Self-Balancing-Robot/  on building a self-balancing robot with uno. However, I bothered by the Bluetooth wiring. I've done Arduino projects with Bluetooth before and all the Hc-05 wirings I've seen have it connected to the Tx and Rx pins.Currently, I have my Bluetooth module wiring like this :   with http://cdn.instructables.com/FSK/AI30/HMMFE6UO/FSKAI30HMMFE6UO.MEDIUM.jpg.
Will the different wiring need a different implementation, the code I see on the chappie instructable link does not have any pin mentions but I'm not sure. Is the chappie wiring fine? should I change my wiring? should I change my code?
I'm confused.

Which code are you reading? At step 5 he wrote

  Complete code can be found on the GITHUB.

The sketch file (here is the direct link) has the following lines:

const int rxpin = 11; // pin used to receive (not used in this version)
const int txpin = 4; // pin used to send to LCD

SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

This means that the bluetooth is using a software serial on pins 11 and 4.

I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to blue with Serial.


H-Bridge vs Motor shield for the arduino Assuming we wish to control a small toy car with an arduino - meaning spinning the right and left wheels forward and backward and being able to break and control the speed, where each wheel has it's own engine (but of course two engines on the same side will run on the same speed and direction).

We saw we have two main options - Buying and wiring up a H-Bridge or buying a motor shield (which is based on one).

Are there any advantages for using a motor shield?

Thanks in advance.

If I were a beginner, I'd go with the Motor shield.

I'm even personaly using the one from DfRobot, which as @Gerben said, is just plug and play.

It also allows you to select the input power for the motors, which can be either from the 5V Arduino pin or from an external battery. This is pretty convenient if you need more than 5V to power up your motors. It can also support 2A of current draw, which is more than enough for small arduino toy cards.

Here is the shield: https://www.dfrobot.com/index.php?route=product/product&product_id=1180&search=2A&description=true


DHT11 sensor works on Arduino Uno, not on LoLin NodeMcu When run this code on an Arduino Uno (clone), everything works.
When I run it on my LoLin NodeMcu, I get the following verbose upload output:

esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM4
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

The only difference I really see is that on the Arduino Uno, the voltage pin is connected to 5V, while on the LoLin, it's connected to one of the 3V pins. Does the DHT11 require 5V?

Edit

So I stumbled upon this list of port mappings. When I change my pin number to 5 (meaning D1), it actually works. Kinda. The numbers outputted are strange. Even when I put the board outside, in about -6 Celcius, it still displays

Temp 247.208 °C
RH 216.208 %

Well, I guess this oddity should be posted as another question. I'll answer my own question here with reference to the weird pin-to-number mapping on the LoLin board.

The datasheet says 3V-5V. 3V is the minimum so I DOUBT that isn't the problem, BUT try to pump more juice into it to see what happens. Never believe the datasheet if these cheap components at 100%.

It does say this though:

  VDD=5V, T = 25℃ (unless otherwise stated)

So maybe....

Link to datasheet.


HEF4094 with 12v Vcc Using old NXP HEF4094BP shift register chips, for the reason of fixing some old hardware. These chips were popular in the 90's because they could accept 3-15V VCC and directly drive series+parallel LED chains. Think: gas station price signs, etc.

I'm green. Using this post and the 4094 datasheet, I've successfully modeled your typical shift register count-to-100 binary, with an LED on each SR out. Powered by 5V, works great. This was phase 1 for me.

For phase 2, I powered the Arduino via 12V (via p30, Vin). Still supplying 5V to the 4094 (Nano pin 27 output), works great.

Phase 3, I need help. I remove the 5V jumper that was from Nano pin 27 going into 4094's VCC pin. In it's place, I run 12V directly from the (regulated) PS and I get NO LED output.  I know I haven't burned anything out because at 12V I get brief "flashes" when I'm "plugging" in the 12V power supply. I can revert to 5V VCC input and it works fine as before.

I've read the datasheet 3X and it's not clear how the chip's output pin voltage is managed when you alter the VCC to be higher (is it limiting current or voltage on the outputs?)

The part of the datasheet you need to understand is this bit:

That's the input logic levels, and as you can see they vary depending on the supply voltage.

At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.

The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.

These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.


How to check if two device has the same address on I2C? I start a new project with Arduino UNO and MCP23017 expander. Using this, I can connect 8 chips on Arduino, by selecting different addresses ( from 0x20 to 0x27 ).
My question is, if I connect two MCP23017 chips with the same address, there is any way to see somehow that I have two chips with the same address ?
I am using a standard I2C scanner in Arduino code, but is nt return me if I have multiple chips with the same address, he see only one chip for example !

Can you please help me with some ideas to check how man chips are connected with the same address?

It's my understanding that duplicate I2C addresses prevent the master from communicating from the slaved devices, so the answer is no.

Instead, connect the devices one at a time, run the I2C scanner, note the address for each, and take note of any duplicate addresses.


What Driver IC to use for 40v 2amp DC motor? I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..

I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor.  By far the easiest way is to simply use a N-Channel logic level MOSFET.  Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground.  The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino.  The low side of the 40V power supply must be connected to the source of the MOSFET.

Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).

Carefully check your wiring; if it is ok you are ready to test it.  The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected.  The anode side connects to the drain of the MOSFET.  When the motor is turned on the LED will light, if it does not reverse polarity of the LED.  As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected.  Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

This helps dampen oscillations
Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
For the MOSFET you need at least 60V with a 10A rating.  This should work with a small heat sink.  If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger)
The other side of the resistor goes to the gate of the MOSFET.
Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together.  The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V.  The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.

Good Luck,
Gil


clear Arduino as a global variable in Matlab I'm trying to use Arduino in Matlab. cause I used Arduino in some function I had to define Arduino as a global variable.

clc,clear,close all;
global a
a = arduino();
.
some functions
.
clear a

at the end of my code I clear the variable but as I run the code again this error appear:

Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

I guess the global function can't be clear by clear command so I tried clear all instead clear in the last line. It works perfect as I run it again and again but as you know this is Matlab tips for clear all command

Using clear all causes MATLAB® to recompile previously cached code,
and can decrease performance.

I've tried delete(a) so the result was:

Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.

In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html

In your case should be: clearvars -global a;


unexpected change of ADC value with multiple voltage dividers (thermistors and pot) So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.

Schematic:

reality:

When I adjust the pot, the ADC value of airPinValue changes, regardless of which analog input it is connected to. meatPinValue does not change. Swapping the inputs that airTempPin and meatTempPin are assigned to has no effect, airTempPin changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.

Code:

#define potPin A0
#define airTempPin A5

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  potValue = analogRead(potPin);
  airPinValue = analogRead(airTempPin);
  if (i == 2000) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

EDIT: much simplified code

EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.

EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.

EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by airTempPin is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at airTempPin goes off...

Also update diagram, pic, and code to match what I'm currently testing with.

EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\

#define meatTempPin A0
#define airTempPin A1

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.

Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.

Try this instead:

#define meatTempPin A0
#define airTempPin A2


How to power board plus module with one battery pack I'm someone who's very new to robotics and the physical side of computers (software guy) so apologies if this is a stupid question. I'm purchasing an Arduino Nano 33 IoT that I'll be using in conjunction with an Adafruit FONA 3G Cellular Breakout (https://www.adafruit.com/product/2687). I'd like to be able to power the entire unit off of one battery pack but my problem is that both the Arduino and the Adafruit 3G unit have separate power inputs. Adafruit's website says that a Lipoly battery is required to run the unit. Is there any way to "pass through" or "split" power between the two units? This way I was thinking I could run everything off of one external battery pack. Optimally I don't have to use a Lipoly battery and I could use a large external battery pack connected to jumpers or a barrel jack.

you can use a breadboard and jumper cable. connect the VCC and GND of battery to a breadboard, do this for your Arduino and sim card module too. just remember they should be in a one row. GND with GND row, and VCC with VCC row
note: this way is okay just for debugging


Connection of serial pin on ATMEGA328P to connector B type(female) D+ and D- Now I am using ATMEGA328P and want to communicate with computer in serial using B connector female (also want to provide power from computer to ATMEGA328P using B connector).

So here is my question. How can I connect D+ and D- to ATMEGA328P's pin No. 2 (PD0/RX) and pin No. 3 (PD1/TX)? In other words which pin should I connect to D+ and D- ? Also is it possible to connect them directly?

Thank you in advance.

The Arduino Uno (and similar boards) have a chip on them that does serial communication via a dedicated USB chip (the ATmega16U2 chip). You can't just connect pins 2 and 3 to D+ and D- and turn that into USB.

You can conceivably do it using V-USB which does USB in software in conjunction with a few extra components.

You can also buy external serial to USB adapters which do the conversion externally. If you Google serial to usb adapter you will find quite a few for around $3.


Piezo not loud enough I'm trying to get 110dB out of a 25khz Piezo Transducer.  This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.

Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!

My code is bit-banging it.  With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.

I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.

However, instead of 110dB, I'm only getting 50dB.

I've tried upping the voltage to 20, and still get the same volume level.  The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).

I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds.  I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.

Here's how I'm connected:
1.  The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino.
2.  The output+ of the Step Up is connected to 1 pin of the Piezo.
3.  The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything.
3.  The other pin on the Piezo is connected to D11 on the Arduino.

I'm Running the following code:

 #include<Wire.h>

const int SPK = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(SPK, OUTPUT);
  digitalWrite(SPK, LOW);
}

void loop()
{
  long startTime = millis();
  for (int i = 0; i < 25000; i++)
  {
    digitalWrite(SPK, HIGH);
    delayMicroseconds(15);
    digitalWrite(SPK, LOW);
    delayMicroseconds(15);
  }

  Serial.println(millis() - startTime);
}

UPDATE:

Ok, I am now set up to look like this:

Is this the next step (ie: Adding an Inducer) ?

The device you pictured seems to be a switch-mode power module which will output 10V DC. Get rid of it before you do any damage.

You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.

This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.

The answer to Push-Pull tone code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.

I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.


What happens if you supply too much voltage to an LED? Say I have an LED that requires 3.5v. What happens if I power it with more voltage?

For example, my Arduino Uno has a 5v pin. If I power the 3.5v LED from the 5v pin, what will happen?

In the most simple terms: it will kill the LED.  However things are really not that simple.

First off, an LED is a current driven device, not a voltage driven device. That is, it doesn't really care what the voltage is, but it does care what the current is.  Of course, too much voltage will kill it - but too much current, regardless of the voltage, will kill it.

It's important to understand that an LED is what is known as a non-linear component.  Things like resistors are called linear because they have a linear relationship between voltage and current. Increase the voltage, and the current increases by the same proportion. Increase the resistance and the current decreases by the same proportion.

However an LED is not like that. A typical Voltage-vs-Current graph for an LED looks like this:

Once the voltage reaches the "forward voltage" of the LED the current flowing through it rapidly increases. As you can see it very quickly gets towards infinity. Above a certain point and an increase in voltage has no real difference in the current. In that example the difference between 3V and 5V would be both infinite and zero. In other words, it's pretty meaningless.

But we're still over-simplifying, and that's because we've assumed an ideal power supply. That is, one that can supply a fixed voltage, but infinite current. In other words, a power supply with zero impedance.

No such thing exists, though.

Every fixed-voltage power supply can be seen as an ideal voltage source with an in-line (series) resistor. That resistor limits the amount of current that the supply can provide before the voltage drops too low.  In schematic terms, it looks like this:

simulate this circuit – Schematic created using CircuitLab

If the voltage of the source is above the forward voltage of the LED it will try and draw an infinite amount of current from the source.  That current will lead to a voltage drop across the resistance RZ, which results in the output voltage of the source being reduced.

It will reduce to be the same as the forward voltage of the LED.

We can, of course, calculate the current that would come out of the supply if we know the impedance of the source, but that's not something that is often known.  So you assume it's low and take precautions.

For example, if we happen to know the impedance of the source is 1Ω (maybe it's stated in the datasheet for the power source...) and the voltage is 5V, and we have an LED that has a forward voltage of 2V (I like nice round numbers), we can work out that:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 3A (I=V/R, 3/1=3A)

3A is way off the scale for an LED, and it will basically melt internally.

So we add an extra resistance to drop more of the voltage at a lower current.

Now if we take the example of powering an LED directly from an Arduino's GPIO pin without a resistor, we can do the same kind of calculations.

We know that we mustn't draw more than 40mA from a pin (absolute maximum), so if we take that as the current that can come out of a pin before it drops below an acceptable level we can work out an estimate of the impedance. Since the datasheet tells us the output level it shouldn't drop below is 4.2V when powered by 5V, we know that the maximum voltage drop at the maximum current would be 0.8V (5-4.2).  So:

R=V/I = 0.8/0.04 = 20Ω.

There. That's an approximation of the output impedance of a GPIO pin on an Arduino.  So we can plug that into our formulae and connect an LED, and we get:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 150mA (I=V/R, 3/20=0.15)

150mA is not massive. It's more than an LED typically wants (20-30mA tops), so the LED won't be happy, but it won't instantly blow at that level. It will be brighter than normal, get hotter than normal, and its lifetime will be much much shorter than normal.

That's not the worrying thing though.  The worst thing is the power dissipation from the impedance:

P=I²R = 0.15²×20 = 0.45W.

That's almost half a watt of heat being generated by the GPIO pin's drivers. If you consider that a half-watt resistor is pretty chunky, if you can picture that power being crammed into the tiny space of a single MOSFET within a silicon chip, you can see how that may become a problem.

It's really not capable of dealing with that level of heat, and the GPIO pin's driver MOSFET goes belly up.  Bye bye MOSFET, bye bye GPIO pin.

As an aside, you would probably also see other strange things happening as the chip tries in vain to deliver large currents to a single GPIO pin. Other areas of the chip get starved of power, power rails drop in voltage, code crashes, etc. All from just one little LED being connected without a resistor.


How do I send MIDI properly with ESP8266? So, I've finally able to send and receive MIDI using Arduino.

My next thing to do was sending 5 pin MIDI to rtpMIDI, and vice versa, using ESP8266, but so far I can't even send MIDI correctly.
So far, I used this library, and it send midi without issues with Arduino Mega. But using Wemos D1, strange thing happens.

this is output of MIDI OX. Pretty sure I wasn't sending MIDI CC.

Here's the code so far :

#include <MIDI.h>

 // Created and binds the MIDI interface to the default hardware Serial port
 MIDI_CREATE_DEFAULT_INSTANCE();

 void setup()
 {
     MIDI.begin(MIDI_CHANNEL_OMNI);  // Listen to all incoming messages
 }

 void loop()
 {
     // Send note 42 with velocity 127 on channel 1
     MIDI.sendNoteOn(42, 127, 1);

     // Read incoming messages
     MIDI.read();
 }

UPDATE : Here goes the settings.

Any reason why this happens? Please help me. Thanks!

Schematics :
Basically I just change the Arduino to Wemos D1 Uno.

NOTE : Probably not the answer you're looking for, but it works for me.

Solution : Move the jumper from 5V to Vin.
Why? I don't know. It just works.

Please notice that this is Wemos D1 Uno, which has adaptor input, which can receive 9-24V.
If you're going to use the adaptor, IT MAY BROKE YOUR MIDI DEVICE!
As far as I know, Vin stands for Voltage Input, and everything from the adaptor is routed there. That means if you use 24v adaptor, Vin is 24v!

I'm only planning to use USB as power supply, so yeah. it works for me.
If you're going to use Vin with external power supply, please use voltage regulator to 5v. Better safe than sorry.

Anyway, since I'm planning to use 6N137 to receive MIDI also on this board, here goes :

  Input voltages greater than 7 V must be avoided to preclude damage to
  the gate oxide of the input stage. This damage is not necessarily
  permanent, but will adversely affect the expected lifetime of the
  circuit. The gate oxide of AHC devices is only 200 Å thick. An input
  voltage of 7 V corresponds to a field strength over the gate oxide of
  350 kV/cm. Although breakdown of the oxide is expected only at input
  voltages above 10 V, electrons tunnel increasingly into the gate oxide
  at field strengths greater than 350 kV/cm, influencing characteristics
  of the transistors and causing failure.

Source : this question on electronics stackexchange.


OV7670 Camera Module - wrong pins? I would like to ask you some helpful informations.

Recently I bought an OV7670 Camera Module.
Unfortunately, this item is not compatible with any tutorial I found in dozens and dozens of sites.

It has 18 pins with these signs:

3.3v   GND
SCL    SDA
VS     HS
PCLK   MCLK
D7     D6
D5     D4
D3     D2
D1     D0
RESET  PWDN

I aint noticed these pins on any OV7670 Camera in any site of tutorial, like youtube or arduino.cc or many others at google searching.
The most comon OV7670 Cameras I found in tutorials have SIOC SIOD instead of SCL SDA, HREF instead of HS and XCLK instead of MCLK.
Did I bought a fake or what do you think?
Please, if any of you, knows how to make it conect or have any useful link, I will apreciate to inform me.
Thank you all for your time.

They are actually named in a different manner.

Your camera module has i2c interface.

SIOC is nothing but Serial Input Clock , same as SCL - i2c clock

Similarly , SDA and SIOD are the same - i2c data

HREF and HS are the same too - Hsync signal

MCLK and XCLK are the same too - system clock

Here is a useful link:

https://www.google.co.in/amp/www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/%3famp_page=true

Cheers !


Using IMU for a small Arduino and bluetooth support I'm gonna start a project with an IMU with a bluetooth support inside a small board (mini or lillypad) and send datas to the mobile phone. But I'm quite new to those kind of technologies.

I'm going to choose a module for handling both operate voltage restriction and memory capacity for both library (IMU and bluetooth).

Any advice obj which arduino / IMU breakout / bluetooth module / battery to use? Or some similar projects?

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

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

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

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

Hope this helps.


Decode VGA port by Arduino Is it possible to read somehow VGA port of graphics card by Arduino? Even with some minimal 320 x 240 resolution and minimal frame rate per second, to convert pixels into numbers (for example) somehow. Who can show where to dig?

Calculation:

320 x 240 resolution (assuming 8 bits for 256 colors) is 76,800 bytes

Assuming a frame rate of 50, that is 50 * 76,800 = 3,840,000 bytes/s

The most Arduino's are 16 MHz so assuming quite some instructions are needed (for converting and doing something) I doubt you will get this frame rate.

Also, you cannot store a complete page, but this may not be necessary.


How to connect an Arduino via an ethernet cable to a laptop directly? Maybe a silly question, because it is a usual topic, but I have a problem with my Arduino Leonardo ETH.

I want to create a web server on the Arduino with the example sketch File > Examples > Ethernet > WebServer. I plugged in the ethernet cable directly to my laptop. So there is no router or switch between them.

I also set the configuration to my ethernet port to the following IPv4 properties:

Then in the example sketch, I changed the MAC address according to the bottom sticker of my Arduino.

byte mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x33, 0xD6};
IPAddress ip(192, 168, 1, 177);

Now when I compile and upload the sketch to the Arduino, everything is working fine until it prints the IP address. According to the IP address which I have set in the code (192.186.1.177), it shows me 0.46.46.46 as you can see in the picture:

This happens when I print that:

Serial.println("server is at ");
Serial.println(Ethernet.localIP());

Do you have any ideas how I could fix this? And why does it show me that invalid IP address?

Thank you in advance.


Using digital pins 0/1 on Arduino Due when writing/reading over serialUSB port I am aware that you cannot use pins 0 and 1 as digital pinouts when communicating over serial via serial.print(), but what if you are using the native port on the due with serialUSB.write()?

Thanks

Yes, you can use 0/1 while using the native USB. The two are completely separate.


Ambiguity in Software Serial HW:
2 Arduino ProMini 16Mhz, 5V
Software serial directly connected using male jumpers on bredboard.

I have creates a software serial port for communication between two arduinos, Parent and child

as per the documentation
http://arduino.cc/en/Reference/SoftwareSerialAvailable

mySerial.available()

should return the number of bytes available in the buffer.
and

mySerial.read();

should give me the byte or return -1 (255) on error.
http://arduino.cc/en/Reference/SoftwareSerialRead

here is my code snippet where i read the values

if(child1.available() > 0){
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

the Serial outputs are for debugging,
The condition for while is true. we go inside.
Now what i receive with child1.read() is the following

ParentReceived Something from child 2
255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

all i see is 255.

what i did:
     I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another
TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.

I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of SoftwareSerial.

It's important to note that only one instance can receive data at any given time. You need to call listen() on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)

See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen


Reading digital port with pullup via Firmata I've got a weird issue, probably something I'm missing but have no clue what.

Got some simple float sensors connected to D2 - D5 on a Nano. Need internal pull-up to eliminate a floating value. Wrote this little sketch to test things:

pinMode(2, INPUT_PULLUP);
int sensorVal = digitalRead(2);
Serial.println(sensorVal);

pinMode(3, INPUT_PULLUP);
int sensorVal = digitalRead(3);
Serial.println(sensorVal);

There's one sensor connected reading HIGH and one reading LOW. This works as expected (displays 1010101010...).

Now I've got this connected to my Raspberry Pi via Bluetooth (BT shield connected to RX/TX) and using Firmata to communicate with the Nano. Code (C#):

_arduino.pinMode(2, PinMode.PULLUP);
PinState result2 = _arduino.digitalRead(2);

_arduino.pinMode(3, PinMode.PULLUP);
PinState result3 = _arduino.digitalRead(3);

Debug.WriteLine($"Result pin 2: {result2} and pin 3: {result3}");

This always gives me two pinstates of LOW, even though I'm absolutely sure it should be reading HIGH as my test sketch is outputting the correct value. This driving me nuts. The Firmata sketch I've got loaded on the Arduino is this one: https://github.com/jsiegmund/submerged/blob/master/src/Arduino%20Sketches/SubmergedCabinetModule/SubmergedCabinetModule.ino. Also tried the latest available version from the firmata repo, doesn't solve the issue. As I've got the BlueTooth shield connected to RX/TX (and wasn't able to change that) I cannot use the serial monitor to provide more debug info. Should anyone know how to change that, would also be appreciated.

Btw for other things, Firmata is working just fine. So the communication itself shouldn't be the issue I think.

Never mind, I found out what the problem is. The Firmata SDK (Remote Wiring) for Windows just completely ignores the PULLUP pin mode. There are PR (https://github.com/ms-iot/remote-wiring/pull/102) which fixes this, now it's working just fine.


Wrong calculation UNO I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes_SJoys, max value of 1023 on any axis) and example would be:

y = 500;
servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?

#include <Servo.h>

Servo servo;
int d2 = 2;
int a0 = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(d2);
}

void loop() {
  int y = analogRead(a0);
  Serial.print("y: "); Serial.println(y);

  servo.write(y * 180 / 1023);
  Serial.println(y * 180 / 1023);

  delay(100);
}

PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.

What you are experiencing is a common pitfall.
You are probably expecting floating point calculations, but what you are writing are only integer ones.

Try with:  y * 180. / 1023.   (notice the dots).

This will work only with constants.

To make it work with anything, use a cast:  y * 180 / (float) 1023

Happy hacking.


Powering multiple servos on external battery I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.

Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.

I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.

I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to.

If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.

If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.

Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.

I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.

After that you will understand a bit better what is going on and why this issue is happening on your configuration.

I cant find the power consummation of this servo so I Cant give much more information.


What is the correct way to create large project files? I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

The LED matrix
A DS3232 RTC
An MSGEQ7 DSP chip
7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.

What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.

Any help would be greatly appreciated, I can upload the source code if its needed.

Cheers

As a side note, I'm using "Sublime Text 3" along with Stino.

Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.

It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.

If it has a lot of interactions, maybe you should put the patterns itself in a different class.

Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class

Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.

Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about SOLID.


LGPL and Arduino in Commercial Products I basically would like to ask this same question (in another context / more generically):

https://www.reddit.com/r/arduino/comments/25my2t/lgpl_and_arduino_in_commercial_products/

Stated differently:

What are the legal implications of LGPL licence in commercial products using Arduino boards (and or Arduino software/firmware)?

and about creating my own libraries for Arduino? (less or more permissive licenses cases for a derivative work)

and lastly, I'm also curious about this statically vs linked library conditions of LGPL (and how this would be applicable in this case)

thanks!

IANAL, but my understanding is:

Any LGPL code you modify you need to make available as source.
Using LGPL code in your project doesn't constitute modification of that code unless you actually modify that code (See above).
Any code you write that is not contained within LGPL code (see above) is yours to license as you wish. That means your libraries are your libraries. Your sketch is your sketch.

So in short, things that must be released as LGPL:

Modifications to the core code.
Modifications to other people's libraries

Things that are yours to license as you wish:

Your libraries
Your sketches

Things you should (if you're nice) provide attribution for:

Arduino API
Third party libraries

As far as hardware goes:

  These files are licensed under a Creative Commons Attribution Share-Alike license, which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license. The Arduino software is also open-source.

Which means if you use their designs within your own design you should attribute it and make it open source under the CC-BY license. Otherwise, if you just use their hardware verbatim there's nothing to attribute - you haven't used their designs, but a commercial product as a component.


Can I use this camera switcher? I am wondering can I use this bicks camera switcher with the arduino since it uses a PWM signal.
If i can do I just put it on one of the PWM outputs or do I need to wire I add something to make it work.
**You can find the user manual here under attachments.**https://store.bicks.us/multiview/20-bicks-s-multiview-duo-fpv-camera-switcher.html

The pwm output of an RC receiver is the same signal used to control a servo. So if you used the servo library with Arduino to control the pwm of this device it should work fine.