If-statement gets ignored? I'm kind of stuck with strange behaviour of my code and I really hope, someone could help me..

Objective
I'm trying to build a (multiple) magnetic stirring device with which I can either control the speed via potentiometer or via serial commands from a python script from pc (usb).
When the speed is set via serial, it shouldn't be possible to interfere with the potentiometer unless a button is pressed to unlock it.

Code

// Constants

const int FanPin[7] = {2,3,5,6,7,8,9}; // PWM Pins 2,3,5,6,7,8,9 for fan
const int PotiPin[7] = {A0,A1,A2,A3,A4,A5,A6}; // Analoge Pins 0,1,2,3,4,5,6 for potentiometers
const int SwitchPin[7] = {30,31,32,33,34,35,36}; // Digital Pins 30, 31, 32, 33, 34, 35, 36 for switches

// Variables
boolean ManualLock = false; // will be true if locked by serial input
int Fan[7][2] = { // [x][] for number of fan, [][0] for fan speed, [][1] for ManualLock
  {0, ManualLock},
  {1, ManualLock},
  {2, ManualLock},
  {3, ManualLock},
  {4, ManualLock},
  {5, ManualLock},
  {6, ManualLock}
};
int temp = 0; // Variable for temporary data
int FanSpeed[7] = {0,0,0,0,0,0,0}; // Variable fan speed
int PotiVar[7] = {0,0,0,0,0,0,0} ; // Variable for saving poti-input
byte bfr[2] = {7,7}; // Buffer for serial data

void setup() {

TCCR2B = TCCR2B & 0b11111000 | 0x01; // Timer2 (Pin 9, 10) @ 31000Hz
TCCR3B = TCCR3B & 0b11111000 | 0x01; // Timer3 (Pin 2, 3 und 5) @ 31000Hz
TCCR4B = TCCR4B & 0b11111000 | 0x01; // Timer4 (Pin 6, 7 und 8) @ 31000Hz

Serial.begin(9600);
delay(100);

// Declaration of Pin Modes
for (int i = 0; i < 7; i++){
  pinMode(FanPin[i], OUTPUT);
  pinMode(PotiPin[i], INPUT);
  pinMode(SwitchPin[i], INPUT);
  }
}

void loop() {
for (int i = 0; i < 7; i++){
  // ManualLock not active -> manual mode
  if (!Fan[i][1]){
    //Serial.print(i);
    //Serial.println(" ManualLock not active");
    PotiVar[i] = analogRead(PotiPin[i]);
    Fan[i][0] = map(PotiVar[i], 51, 1023, 60, 255);
    //Serial.println(Fan[i][0]);
  }
  //ManualLock active -> unlock by pressing button
  if (Fan[i][1]){
    temp = digitalRead(SwitchPin[i]);
    if (temp == HIGH){
      Serial.print(i);
      Serial.println(" ManualLock will be deactivated");
      Fan[i][1] = false;
      Serial.print("Fan[i][1]: ");
      Serial.println(Fan[i][1]);
    }
  }

  // fan off @ low poti setting
  if (PotiVar[i] < 50){
    Fan[i][0] = 0;
  }
}

// look for serial data

if (Serial.available()){
  Serial.println("Something's there!");
  Serial.readBytes(bfr, 2);
  delay(1000);
  Serial.print("Serial data: ");
  Serial.println(bfr[0]);
//  Serial.flush();
}

//Serial.print("before loop bfr[0]: ");
//Serial.println(bfr[0]);

for (int i = 0; i < 7; i++){
  if (i == int(bfr[0])){
    Serial.print("i: ");
    Serial.println(i);
    Fan[i][0] = int(bfr[1]); //set fan speed variable
    Fan[i][1] = true; // activate ManualLock variable
    byte bfr[2] = {7,7}; // clear buffer
    Serial.print("bfr[0]: ");
    Serial.println(int(bfr[0]));
  }
}

for (int i = 0; i < 7; i++){
  analogWrite(FanPin[i], Fan[i][0]); // write fan speed
  }
}

Error(s)

When I send a command via my python script, the speed is set correctly and I get the following output:

Something's there!
Serial data: 0
i: 0
bfr[0]: 7
i: 0
bfr[0]: 7
...and again and again and again...

Which means, although i "reset" my buffer variable to something that should prevent entering the if-statement, it will somehow fulfill the "if (i == int(bfr[0]))" condition.. but why?
If any further information is needed, i'll happily provide that.

This (inside your for loop) does not do what I think you think it does:

byte bfr[2] = {7,7}; // clear buffer

You think it sets the contents of the bfr array you declared at the top to {7,7} but what it actually does is declare a new byte array in that scope, containing the values {7,7}. It's not used and is immediately thrown away again.

I would expect the compiler to warn about it -- does it?  (If so, take it as a lesson not to ignore compiler warnings!)

I think you want to replace it with

bfr[0] = 7;
bfr[1] = 7;

or something equivalent.


ESP8266 still connects to wifi even after flashed with empty sketch So, my wifi is a hotspot password protected. I was developing a program until I decided to comment the ssid and passwords from it, to prevent the ESP from connecting to the internet. But then it still connected. After some debugging, I decided to upload an empty sketch. It still connects to the hotspot!

What is going on?! How does it still know my SSID and password when loaded with an empty sketch!?

The Espressif esp8266 SDK remembers the SSID and password on flash to start connecting immediately after boot. The WiFi channel is stored in the RTC memory (cleared on power down)

You can control this with WiFi.persistent() and WiFi.setAutoConnect().


UNO R3 board not detected When I plug my new UNO R3 board into a PC's USB port it powers on but no device is detected by the operating system. I've tried on three different PCs, Windows 7, 8 and 8.1 with multiple different cables. My guess is that the board is defective but would appreciate any pointers you can give.

It shouldn't be detected by Windows. You must install the software for your operating system here. Scroll down to Arduino 1.0.5 and click on windows. after installing, open up the Arduino IDE (it should be labeled "Arduino" on the desktop or start menu/screen). Plug in your board, and go to Tools> Serial Port. Select COM3. If it is grayed out, it has been auto-selected for you. The reason it won't work without the software is that the UNO and other Arduino boards don't have "true" USB. They basically emulate a serial port over an usb connection.


Understanding flow of current with pull-up and pull-down circuits I am new to all of this and was trying to figure out what was happening with pull-up/pull-down circuits.  I think I understand what happens when the board handles the pull-up/pull-down but I wanted to try to build the circuits.  I got help from another forum.  Once I made the circuits, I found that I don't understand the path that the voltage is traveling.  I have 2 examples with multimeters attached.

Pull Up

I understand the press of the button connect circuit to ground.  But why does the voltage everywhere go down to zero when it is connected to ground?  Does it have something to do with the multimeter can't read the voltage because the current is taking the path of least resistance - which I have read is a myth?

Pull Down

When compared to the Pull Up, why does the voltage go to 5 before the yellow wire when the button is pushed?  Isn't it connected to the ground again which seems like it should cause the same scenario as the Pull Up where they all read zero.  Or does the resistor before ground have something to do with this.

I know nothing about electronics.  Some information and links where I could find more information would be great.  Thanks.

All the gifs are screen recordings from circuits I built with circuits.io.  I want to get into making somethings but wanted to practice first before I spent any money.

It's very hard to read your circuit, because there are wires everywhere. However this is effectively what a switch and a pull-up resistor looks like:

Due to the pull-up, pin 8 on the Arduino (which the switch is connected to) is normally pulled-up to 5V if the switch is open.

When you close the switch pin 8 becomes 0V, thus your meter reads 0V.

On the other hand, with a pull-down resistor, the circuit looks like this:

Now pin 8 is normally zero volts with the switch open, and when closed pin 8 is connected to 5V to pin 8 becomes 5V.

See my tutorial on switches for more details.

  What happens with the flow of current and the resistor to make one example read high and the other low.

Imagine a door with a spring on it to close it. The spring is like a pull-up (or pull-down) resistor (depending on whether you are trying to keep the door closed or open).

The spring gently pulls the door shut. However if you barge out of it with a handful of pizzas in your hand your override the spring. In the absence of the spring the door would just flap in the breeze, sometimes opening and sometimes closing.

The point is, a person is strong enough to force the door open, despite the spring. Similarly if you close the switch you override the pull-up (or pull-down) resistor.

  Where does the 5V go when the switch is closed.

It flows through the resistor to ground (or 5V depending on which one you are talking about).

  When the switch is open in the pull up example - is voltage going through the resistor? From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.

Voltage doesn't "go through" a resistor, current does.

With the switch open, effectively a tiny amount of current goes through the resistor to pin 8. It is a "high impedance" input which means it puts a very small load on the input. Thus there is a very small voltage drop over the 10k resistor, and almost the full 5V is presented to the input pin for reading.

To work out the exact amount, we can look at the datasheet which says that the maximum leakage current through an I/O pin at 5V is 1 µA. Now using Ohm's Law we can find the voltage drop over the 10k resistor:

V = I * R
V = 0.000001 * 10000
V = 0.01 V

Thus with 5V at the 5V pin of the processor, and a (maximum of) 1 µA consumed at pin 8, it will therefore have 4.99 V at the pin, which therefore reads HIGH.

With the switch closed, then we use Ohm's Law to calculate the flow through the resistor:

I = V / R
I = 5 / 10000
I = 0.0005 A

Thus 0.5 mA flows through the resistor with the switch closed. This is not enough to damage the resistor, or make a significant load on the 5V line.

I think you are getting confused (as I did when I was young) that a big resistance (like 10k) must "resist" a lot of voltage. It is easy to think that after going through 10k resistance there can't be much "voltage" left.

The fact is, though, that the voltage on the other end of a resistor is proportional to not only the resistance (R) but also the current (I). This is Ohms's Law (V = I * R)

So, if the current is very small (as is the case with an input pin) then the voltage drop over a resistor - even a large one - is very small.

So, the idea of a pull-up resistor is, that with no external influences (like a switch) then after passing through 10k resistance, there is still 5V at the other side.

Let me issue you with a challenge. Find a voltage source (eg. a battery). Measure it with your multimeter. Let's say you have a 5V source which is the Arduino 5V pin. Now get a 10k resistor. Put it in series with the 5V source. Now measure it on the other side of the resistor. Depending on the quality of the meter (and thus how much current it takes to measure a voltage) you will get very close to the same voltage reading. In my case I had 5V on one side of the resistor, and 4.99V on the other side. This is exactly what my calculations above predicted.


Arduno Uno voltage in via VIN pin or DC power? I have an Arduino UNO. It has VoltageIN on a pin. Is there any difference between powering my UNO through VIN or powering it through the DC port?

The docs only say this,

  5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So it seems to imply VIN/USB/DC in all go through the voltage regulator? Is there any difference then?

Is there any advantage to running a variable power supply through an adapter like this:

Or should I just go through VIN?

DC Jack has a Reverse Protection Diode, that drops 0.7V at usable currents. The VIN does not. Both go through the on board LM7805 or similar linear regulator. The USB does not, but it does go through a P-Channel Mosfet used to switch between USB and DC/VIN power before connecting to the 5V rail. The 5V pin bypasses the regulator, Diode, and P-Channel Mosfet completely.

The advantage of the DC jack is that the Reverse Protection Diode is used, preventing reverse voltage problems if you wire it wrong.


Running Steppers with servo I'm doing a project which is automatic box carrier. It will hold a box from a location and move it next to it. Kind of cnc work. Locations are fixed it just has to run the orders. I want to send an array of integers and manage them in the switch under main loop. for example

  orders[0]=2;
  orders[1]=2000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=7000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=90;

  orders[10]=1;
  orders[11]=2000;

will be my orders array and here is the code i want to run. When I upload code to arduino steppers and servo doing fine until orders[8]. When came to that order; first servo goes to 30 degrees then goes to 0 and click sound starts. After that steppers are not doing remaining steps.

#include <Servo.h>
Servo myservo;

int distance=0;
int code =0;
int orders[10]={};
int thisStep=0;
int thisVal=1;
int pos = 0;
int currpos=90;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  digitalWrite(4,LOW);
  digitalWrite(5,LOW);
  myservo.attach(9);

  orders[0]=2;
  orders[1]=7000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=2000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=30;

  orders[10]=1;
  orders[11]=2000;

 /* orders[12]=2;
  orders[13]=5000;*/
}

void loop() {

  code = orders[thisStep];
  switch (code){
    case 1:

    go(orders[thisVal]);
    thisStep = thisStep + 2;
  thisVal = thisVal + 2;

    break;
    case 2:
     Serial.println(thisVal);
    goReverse(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;

    break;

    case 3:
    goServo(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;
    break;
  }

}
void go(int dist){
  digitalWrite(2,LOW);
  digitalWrite(4,LOW);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(10);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(10);
  distance = distance+1;
  Serial.println(distance);
  }while (dist>distance);
 distance=0;
 delay(500);
}
void goReverse(int dist){
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(300);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(300);
  distance = distance+1;

  }while (dist>distance);
  distance=0;
  delay(500);
}

void goServo (int degree){
  myservo.attach(9);
  myservo.write(degree);

  delay(300);
   myservo.detach();
  /*if (currpos > degree)
  {
    for (pos = currpos; pos >= degree; pos -= 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }
      delay(500);
  }
  else if (currpos < degree)
  {
    for (pos = currpos; pos <= degree; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }

  }
  currpos=degree;

*/

}

Thanks.

Your problem here is that you have an array of 10 bytes, which works fine, only that in your loop you don't stop or check that you are within that array.

If this is supposed to run forever, you could add a line like this at the end of your loop:

if (thisStep > sizeof(orders)-1) thisStep = 0;

(-1 because you have an array of 10, which are from 0-9, sizeof will return 10)

this will make it start from the beginning again.


Is there a radar - like sensor that can tell me the distances of multiple things around the sensor? I'm trying to develop something that requires accurate distance measurement of objects around the center of the contraption. However, I cannot find any way to achieve this other than using a bunch of infrared distance sensors. Really, I'm looking for something that costs at most $200 and is compatible either with arduino, PC, or raspberry pi.

This may not be the place for this, if not, please inform me.

Thanks in advance!

What you're looking for is called lidar - but it's not cheap. RPLIDAR is the current price leader for non-hacky solutions, and I haven't seen it for much less than $400 anywhere.


Powering 4 servos with an external source I am powering 4 tower pro sg90's and I NEED them to run at maximum torque for at least a few minutes, so 4.8volts. I am wondering how many AA batteries I will need to power all 4 servos at maximum torque for a short amount of time (like 5minutes type of thing). The servos are basically lifting different 3d printed objects.

When choosing a power source, you'll have to consider a few requirements:

Required max amperage (max draw of power)
Required voltages (AC or DC, and available voltages)
Does it have to be mobile?

How long does it have to be powered? (how to recharge/refuel?)

Also see this tutorial it explains that you need a certain voltage for a device to work, too high voltage can result in permanent damage. For amperage, you need to have at least the minimal required, too much is no problem.

Since you don't really have a problem to fix, I can only tell you what I've worked with or what I've liked.

Bench supplies

Bench supplies are great while prototyping, they don't run out (like batteries) and can have a large range of voltage and supply a lot of power. I've looked around to get a nice bench power supply, but I found that they're quite expensive. If you want a variable supply that can do up to 5A, it'll cost you some real money (though it usually is well worth it).

Though my setup has always worked great for me, I use:

converted PSU (PC power supply)
Adjustable step down module

For the PSU, you could also add indicator LED's, they're great because they can supply very much power at very convenient voltages (12v, 5v, 3.3v, -12v). Also since it's a PSU it has overcurrent protection and thus is reasonably safe.

I've also bought the "adjustable step down module" from E-bay, you can power it from a 24V or 19V source like a laptop charger. You can set the output voltage and output max amperage. You can even see when the supply is limiting on power or on amperage. (So you can check if your device is taking more current than set)

"Moving" projects

The easiest thing here is (multiple) batteries, check the tutorial of sparkfun again. If you put them in series, you will sum up the voltage. If you put them in parallel, you will sum up the capacity.

I think batteries are the easiest way to power your device. You can check different types of batteries, they have different voltages and "ampere hours". Battery holders are cheap and you can easily replace them if they run out.

On the subject of rechargeables, I would go with an Ni-Mh pack. I've got a Ni-Mh pack for airsoft and it's very reliable and easy to charge. Li-Ion requires much more care in handling and charging.

Other options can be solar-cells or other harvestable energy, but these often aren't really viable.

Extra

When starting to move, a servo can suddenly pull a lot of power. Not all supplies can handle this well. So the other servo's may "jiggle". Often, it's good to have a capacitor that can act as a "reservoir" or for smoothing. Same goes with devices that reset in some scenario's.

*I hope this gives you an idea on some possibilities, I haven't highlighted all options (there are too many), you should check tutorials/video's and see what works for you.

For example, check this instructable that focusses on some (analog) points that I didn't mention.*


Looking for a game application oriented display for Arduino Mega I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.

I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:

*(0x12)=0x34 // Sends 0x1234

However, I couldn't find where to buy that specific one.

I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!

The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).

It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).

It should be either:

Monochrome
Color display with MS Paint colors if it has equal to or less than 256 colors
Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.

If anyone knows where to buy it, please comment.
Thank you for your time.

I'd suggest, if you haven't done it already, to take a look at what is supported by uGFX.

If you find any HW meeting your needs, you can at least be sure that it is supported.


How accurate is arduino time keeping? I want to use my arduino to turn a light off for 16 hours and on for 8 hours. I know the general code, just using delays and the relay shield code as well. I want to know how accurate this will be? ( I tagged uno and leonardo, as I have access to both)

There are multiple versions and "clones" of the Arduino, and each one will probably use different components. The time you refer, in this case "millis()" I believe, is maintained from a timer interrupt, which is derived from the main clock (normally 16Mhz).

The main clock on your board might be generated by a ceramic resonator, which is not very accurate: around 0.5%-1% error. It also might be from good quartz crystal, with up to 0.001% accuracy. Those variations on the frequency source will produce some drift over time... Like your watch needs to be readjusted from time to time.

Another factor that affects accuracy, including for RTCs using a 32.768KHz crystal, is the temperature. Here an Application Note on this: http://www.st.com/content/ccc/resource/technical/document/application_note/55/e2/3d/2a/87/ab/4d/e1/CD00232494.pdf/files/CD00232494.pdf/jcr:content/translations/en.CD00232494.pdf

Your application might not require too much precision, and you could simply write a sketch to print the time every second on the serial... let it run from one hour, one day, and check how much drift you're getting. After that will be easy to estimate how much drift you'll have a after a month.


Serial Monitor appears unreadable characters Hello

My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

It can have many reasons, but the most likely are:

You set the baudrate wrong
You set the stop/start bits wrong
You send wrong data
The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.


How can I make this button toggle the position of a servo? I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.

void setup() {
  myservo.attach(8); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // Initialize the Serial port at 9600 baud.
  pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}

void loop() {
  buttonState = digitalRead(9);
  if ((digitalRead(9) == LOW) && (button_mode == 1)) {
    // Check Digital pin 9 to see if it's pressed.
    pos = 150; //set servo position variable to 150
    myservo.write(pos); //set servo postion to 'pos'
    delay(1000); // wait 1 second
    button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
    Serial.println("Button has been pressed."); // and report that to the serial monitor.
  } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
    pos = 50;
    myservo.write(pos);
    delay(1000);
    button_mode = 1; // Button was down before, but is released now. Set the button to
    Serial.println("Button has been released"); // released and report that to the serial monitor.
  }
  delay(100); //small delay to account for button bounce
}

Do something like this:

int angles[2] = {0,180}
bool state = 0;

then:

if(button == PRESSED)
  state = !state;

finnally, to control the servo:

Servo.write(angles[state]);


Two rpm counters with interrupts Can I use two interrupts on to count rpm square signals coming from two hall effect sensor modules (that has built in comparators to generate square signals) ?

What if two signals come together ? Will they conflict with each other ?

Will this work on attiny85 ?

I used to use two interrupt to read encoders where the two signals never conflict with each other

Thank you in advance

There is more than 1 option how this can be done. A frequency of 40Hz is relatively slow, so you are not limited by this.

In my comment I first suggested to use the Timers/Counters with the signal as input, but I found, that this is only possible with one of the two timers of the ATtiny. Despite that, I will add this to the answer for information (and because this can be possible on other boards with more timer input pins).

Using the PinChange interrupt and doing counting in software: Since the ATtiny85 has only 1 external interrupt, you have to use the PinChange interrupt for this. If activated, this interrupt will trigger, when ever one of the pins 0 to 5 changes it's value. You can mask away any pin in this range, so that it doesn't count. You would use 2 pins and mask the others away. In the interrupt routine you would check the state of the two pins and increment the respective counter:

volatile unsigned int counter1=0;
volatile unsigned int counter2=0;

ISR(PCINT0){
    if(digitalRead(input_pin_1)) counter1++;
    if(digitalRead(input_pin_2)) counter2++;
}

(Note the volatile declaration of the variables, because they change inside of an ISR). The counterX variables can then read in defined time intervals (for example very second) to calculate the RPM. Of course, executing code in an ISR can mean, that you miss another interrupt. During the short time period between the first interrupt and the completed execution of the ISR no other PinChange interrupt will get registered. If that is a problem is dependend on how often the pulses will be inside this small range. If that only happens very rarely you can ignore that, since it introduces only very small errors. You can even make the ISR faster by not using digitalRead(), which takes a bit to execute, but using direct Prt Manipulations. That makes the error more unlikely.

The interrupts have to be configured for this, so you need a setup code like this (this will use direct manipulation of the status registers of the ATtiny):

PCMSK = 0b000110; // Mask all pins for this interrupt,except for PCINT1 and PCINT2
GIFR &= ~(1 << PCIF); //Clear PinChange interrupt flag
GIMSK |= (1 << PCIE); //Enable PinChange interrupt

In the loop function you can use the non-blocking code style from the BlinkWithoutDelay example, to regularly calculate the RPM from the counter values;

void loop(){
    if(millis()-timestamp > INTERVAL){
        GIMSK &= ~(1 << PCIE); //Disable PinChange Interrupt, so that we don't get interrupted by ti
        unsigned int countervalue1 = counter1;
        unsigned int countervalue2 = counter2;
        counter1=0;
        counter2=0;
        IMSK |= (1 << PCIE); //Reenable PinChange interrupt
        // Do the calcuation here with countervalueX and show the result somewhere
    }
}

It is important to disable the corresponding interrupt, when you are accessing the counterX variables, because you have to prevent them from changing midway during processing. To keep this short, they are just copied to local variables and then released again.

Attention: the following suggestion doesn't work on an ATtiny85, since it only has 1 timer input pin.

Using both available Timers/Counters and the signals as clock input: If you really don't want to miss any pulses, you can utilize two Timers/Counters. Timers and Counters are the same. A counter increments a status register on every falling or rising edge (depending on the configuration) of a signal. If this signal is derivated from the chips clock, this is called a Timer. You would use it as a Counter, feeding each square wave to one Counter input pin. To actually get the RPM, you can either check the counters value (TCNT0) after defined time interval, or you can activate the overflow interrupt of both timers and measure the time between the overflows.

Since here the edge-sensing is done in hardware, no pulse can be missed. On the other side, this way needs more configuring and blocks 2 precious timers.

When working with the status registers in such a direct way, the datasheet of the ATtiny85 is a must read.


Convert Binary to char I'm reading a text file saved on my ESP8266 device (using LittleFS).
while (myFile.available()) {
        Serial.write(myFile.read());
    }

My goal is to save file content ( each line ) to a String / char array.
myFile.read() returns a binary - and I'm looking for a quick and elegant way to do so ( as in Serial.write which converts it to text ).
Guy

myFile.read() returns one character. That character can be represented as a number (such as 65 for 'A') or a character, or whatever you want. Everything is just a number.
Letters are just our personal representation of certain numbers as humans. You could think of it as the numbers represented in base 256, where each value between 0 and 255 is assigned a unique symbol.
Serial.write() just passes that number verbatim to the computer which then maps it in the serial monitor to the corresponding letter in the ASCII table.
Thanks to the object-oriented and polymorphic nature of the Arduino API (see C++ Polymorphism) there is no difference between reading from a file and reading from serial. They all inherit the same Stream class that gives you the same functions regardless of what you're reading.
So you could, like Serial, read each byte from the file one at a time until you reach the line ending character(s) (\n for a Unix file, or \r\n for a Windows file) and append each to the end of a string (either a String object, which is frowned upon, though less so on more capable MCUs like the ESP8266 and ESP32, or a char array).
Alternatively you could use one of the helper functions of the Stream class, such as readStringUntil(), which reads an entire string up to (and discarding) the specified terminating character and returns a String.
However both those have problems when it comes to building up an array of all the results, especially if you don't know beforehand how many lines there are in the file - since in C++ arrays have a fixed size.
A better solution, if you really do want it all in RAM (see below), might be instead to, at first, forget the idea of lines and just read the entire file into memory. Once it is in memory you can read through the entire block of data counting the number of \n bytes (and add one if it doesn't end with \n). That will give you the number of lines in the file.
You can then allocate an array of pointers with the same number of entries as there are lines.
From there you can use strtok() on the data to split it into chunks on the \n bytes and assign each chunk to one of the pointers in your array.  That array then becomes a kind of index to the data.
But one has to ask... why do you want to store this data in RAM anyway? You have it in flash, and that is quite fast to access (not as fast as internal flash in a traditional MCU, but still many times faster than an SD card for example). If ease of navigating the data is your goal, maybe you should be thinking of better ways of storing your data. Depending on what that data is maybe a fixed size record based file structure using a struct to manipulate the data would be a better solution - then you can just seek to multiples of the record (or struct) size to almost instantly get to different entries in the file.
If it's textual data then maybe reading through the file and recording the file offsets of the start of each line in an array (note: two passes - one to count the lines for allocating the array and one for recording the offsets into the array) similar to the indexing of the data block described above would be a better solution. That way you're only storing 4 bytes per entry in your array rather than all the data. Seeking is instant (just seek to the offset stored in the array for the line you want) and you're not having to store all the data in RAM.


Can I use WTV020 sound module as SD card reader? I want to try this example, A Simple Function for Reading CSV Text Files, in order to read a .csv file from an SD card, but I don't have the SD card reader module and can't find it in my country.

What I have found everywhere is this sound module, WTV020-SD, and I wonder if I can use that to read a single .csv file from it, using the SD Arduino library. I checked the module's documentation and there's nothing about it in there.

It seems unlikely, for if you compare the schematic of the WTV020-SD (card reader part only) from the data sheet that you provided:

to the schematic of a bog standard SD card reader:

they are not the same. Instead of interfacing directly to the Arduino, as the standard SD card reader does, the WTV020-SD has additional logic, in the form of a WTV020SD-20S IC.

Therefore the code on the Arduino forums is highly unlikely to work.


Wemos D1 mini and JSN-SR04T-2.0: Type of power supply affects the sensor readings Pretty similar to what is described here I have the strange problem that my sensor readings are affected by the type of power supply I use.
Whenever I connect my D1 mini through USB with laptop everything works fine. The readings make sense and are quite accurate.
But as soon as I disconnect it from the laptop and use a USB power supply (I tested different ones) the readings do not make sense anymore.
I also tried to apply the sketch to a NodeMCU board. The results are the same. So I assume it has something to do with either the sensor or the ESP 12E.
Any suggestions?

Try a different supply or computer, it sounds like that one has a lot of ripple and or noise on it.  Not all USB power supplies are clean and some do not have much filtering.


SPI with a level converter in the other end of connection I have an Arduino MEGA hooked up with a NRF24L01, and working nicely, talking with another Arduino Uno. It works as described, power supply to 3.3V, and SPI lines (MISO,MOSI,CLK) connected directly to the Arduino;

However, when I hook up a level converter in the end (5V to 3V, bidirectional) (making the NRF module in the middle, like in a T connection), the module stops working, and I don't know why. How does the level converter module is interfering in the connection? Is there any way I can prevent this and use it?

I intend in adding in the future, modules that talk in 3.3V SPI;

This is the level converter I'm using:

(source: at-the.space)

I suspect it is because of the pullups (5 think that these 10kΩ resistors are pull-ups, but I'm a noob in that part), but I really don't know if that is the problem, as the seller advertises it as being compatible with SPI, I2C, and UART. I have successfully used these for a UART.

I have checked Slaving multiple Arduinos via SPI and tried using an external 5V supply, and a 3.3V supply, but no dice.. However, the 3V side has no connections to it; But, being bi-directional, I don't think there is a problem with this...

I found that 74HCT245D works very well for this, but I'd like to know why with the level converter from JY-MCU this won't work.

Providing the library and connections just in case (the module works without the level converter):

Library & sketch comes from Optimized High Speed NRF24L01+ Driver Class Documenation.
Connection:

NRF2401 Pinout:
NRF24l01 http://ralphfox.at-the.space/imglink/nrf24l01.jpg
My connection:
Arduino with NRF24l01 and Level Converter  http://ralphfox.at-the.space/imglink/nrf_bb.png

More than probably your level shifter is not fast enough.
A level shifter uses a mosfet to copy signals from one voltage level to the other, but each mosfet has a latency or, if you prefer, a rise time.
Your board probably doesn't use a fast switching mosfet and so the SPI protocol (which is a quite fast one) is not copied correctly.

On top of that you actually don't need a level switcher for the nRF24 modules: the power pin must be limited to 3.3V, but the signal pins are 5V tolerant.
This means you only need a 3.3V voltage source and all the remaining connections can go directly (and safely) into your Arduino board.

UPDATE: the speed concept still applies, it doesn't matter which side of the connection you are using. A mosfet has a little capacitance which slows down the signal transmission: higher the capacitance, slower the maximum data rate.
The cheap chinese level shifter is not designed for high speed communication, while the Texas Instrument device is clearly designed for high speed.
If you look at the SN74HCT245 datasheet you'll notice the switching speed is reported for 50pF capacitance and ranges from 8ns to 16ns: that's the time needed to build enough charge in the switching circuit.


How to read Negative number with serial.read how i can read negative number with command Serial.read()?
beacouse i with  this

    char tmpChar = Serial.read(); //read incoming character from serial port
    if (isDigit(tmpChar)) { //check if the in character it's a number
        setpoint =  (setpoint  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
      }
if (tmpChar == '\n' || tmpChar == '\r') { //if CR or LF was received
    if (setpoint > 0) {
      tmpChar = "";
      Serial.print(setpoint);
      Serial.println(" NUMERO STEP IN AVANTI");

    }

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i insert the number of step in serial input

i can read only positive number. Thanks for help

how suggest Majenko i made a partial solution :

char buf[8];
int valore = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() >= 8) {
    for (int i = 0; i < 8; i++) {
      buf[i] = Serial.read();

    }
    String str();
    if (buf[0] == "-") {
      valore = (atoi(buf)) * -1;
      Serial.println(valore);

    }
    else {
      valore =  atoi(buf);
      Serial.println(valore);
    }
  }
}

but the problem now it's the static array ,
unpleasant to use

You could do something like this:

static int setpoint;      // the partially read setpoint
static bool isNegative;   // whether it should be negative
void applySetpoint(int);  // apply the setpoint when fully read

char tmpChar = Serial.read();
if (isDigit(tmpChar)) {
    setpoint =  (setpoint  * 10 ) + tmpChar - '0';
} else if (tmpChar == '-') {  // minus sign
    isNegative = true;
} else if (tmpChar == '\r') {  // line terminator
    if (isNegative) {
        setpoint = -setpoint;
        isNegative = false;  // reset for next read
    }
    applySetpoint(setpoint);
}

Note that this is not very robust: it will happily interpret "3-2" as
meaning "-32". Note also that I assumed your terminator to be '\r', you
may be using another one.


How to call URL with Arduino Ethernet shield? I'm working on Arduino and Ethernet shield.

I need to call a URL. How can do it? (This URL is HTTP API to send an SMS to my phone).

url:
http://api.clickatell.com/http/sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello

You need to use the EthernetClient. link

The exemple using your API call is:

if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
}

Full example from Arduino.cc docs:

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}


Understanding Digital IMU 6DOF sketch I am looking at the following code and getting confused by a few elements in it:

1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?

2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?

    #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

any help would be greatly appreciated!

The writeTo functions

The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.

Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.

The Bitwise ops

These don't set the number of bits we are reading per se, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.

(((int)buffer[0]) << 8 ) | buffer[1];

Whats happening here is that buffer[0] is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original buffer[0] are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator |, which will turn on any bits that were set in buffer[1] in the result. Since the bottom 8-bits were 0's from the shift, this just copies buffer[1] in exactly.

The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.


How to slowly change direction of the stepper motor with AccelStepper? I know that direction can be changed with
.setSpeed(speed);
... //check input
.setSpeed(-speed);

I need to slowly decelerate and accelerate backwards, so I have to use
.setAcceleration(200);
...
.setMaxSpeed(speed);
... //check input
.setMaxSpeed(-speed);

but documentation told that .setMaxSpeed argument Must be > 0.
So how to properly change direction with deceleration? Probably I have to use .moveTo with some very big values

I have tested it on real motor, and it works as I want with function .moveTo . Speed slowly changed from +maxSpeed to -maxSpeed acording to Acceleration
#define maxSpeed 1000
#define Acceleration 500
............
void setup(){
  stepper.setMaxSpeed(maxSpeed);
  stepper.setAcceleration(Acceleration);
}
void loop() {
 ............
 if(bDirection!=bDirection_last)
 {
  stepper.moveTo(bDirection?6000000:-6000000);
  ...........
 }
 stepper.run();
}


Cutting off OneWire/SDA line with transistors I am developing a pcb for a design I am working on and I need to share a pin to be used by a ds18b20 (onewire) and some possible I2C sensors. There would be just one of each at a time.

I was thinking about using a couple of transistors. One would cut or enable ds18b20 data line and the other one, the same for SDA line. So I would enable the first one and disable the second one or viceversa.

Do you think this is possible? I don't have transistors right now to test it. I have to order some of them. I was thinking about a bd228. Would this add some errors/delays/whatever in signal information? A kind of distorsion I mean. Or should it work?

EDIT: I will try to explain a bit my project.

My idea is to have a box with 5 sockets. Each one of them will be a different data input. They should be able to use a wide variety of sensors, ds18b20, dht22, open/close door (1 or 0 signal)... Also I would want to include some I2C sensors.

I was thinking about BME280 for example.

My idea is that the user could set which sensor is connected each time so the arduino can switch transistor behaviour to allow the connectivity to the digital pin or the I2C SDA (or SCL) pin.

I was thinking about using an I2C multiplexer to allow multiple BME280 to be at the same time so the first line would go to the socket1, second line socket 2...

For multiple I2C busses, it is allowed to share a single SCL and have a separate SDA line for each I2C bus. That means that as long as the SDA is inactive (high), you can do with the SCL whatever you want.

It might even be possible to share the SCL signal for I2C and 1-Wire, and use both. The SCL signal would then also be the 1-Wire signal. The I2C pulses are probably shorter than the start pulse of the 1-Wire. You would also have to do it right in the software to switch the function of the pins. As far as I know that has never been done, so you might get into a lot of trouble.

Transistors are not the right choice to multiplex signals, and the BD228 is definitely not okay. The I2C bus is a open-collector or open-drain bus with a current of maximum 3mA. The 1-Wire bus is roughly the same. It is possible with mosfets or with multiplexers (see: Nick Gammon about multiplexers). However, if you are going to add extra hardware there are probably better solution than combining I2C with 1-Wire.

Have you thought about the voltage levels ? Are you using a 5V Arduino board ? Most sensors are 3.3V. The DS18B20 will work with voltages as low as 3.0V, so 3.3V is no problem for the DS18B20.

Tell us what else is connected to your Arduino board. I'm sure there are better solutions.

Could you better specifiy what it is that you want to achieve ? When there is only I2C sensors or only 1-Wire sensors connected, you could run a i2c-scanner to check for I2C sensors. If nothing is found, do a Wire.end() and start the OneWire using the SCL pin. That could be done during startup and then you don't need extra hardware.

How long are the wires ? The 1-Wire bus can have long wires, but the I2C bus can only have short wires.


Programming an Array of ATTiny I am designing a board for my electronics project and i am using a number of ATTiny85 for it. The ATTiny's will be SMD so i will not be able to remove them for programming.

Moreover all of the pins of my uCs will be used for connections (apart from reset).

Is it possible in this case to achieve that, any ideas and suggestions are welcome

EDIT: Well, Vcc and Ground will be common, i will be using an external oscillator for all of them, the reset pin will be free, the other three pins will be used for gpio communication between the attinys.
I am connecting about 10 attiny in a daisy chain kind of thing

As long as whatever you're connecting the MISO, MOSI, and SCK pins to doesn't mind being driven externally, you can still program the ATTiny in-circuit - just break out those pins with reset to a standard 6 pin header and program them that way.

If one or more of those pins can't be driven externally (eg, because they're connected to another device that drives them and has no output disable), you'll need to add a tristate buffer IC between the MCU and the other device, or some jumpers you can remove when you want to program them.


Arduino OOP and [this] keyword Lets say I have a sketch called mysketch.ino with these contents:

String globalString = "ThisisGlobal";
void setup(){}
void loop(){}

How can I pass THIS sketch mysketch.ino as an object or its reference to a .h file named
StringChanger.h with the following contents, so that StringChanger.h can change somevariables belonging to mysketch.ino.

class StringChanger{
   template <typename T> // or type of mySketch.ino i don't know what i'm doing
   void changeString(T t) {  //a Reference Or Object Or Whatever
      t.globalString = "GotYouAndChangedYou";
   }
}

I wan't to have simple usage in the mySketch.ino.
For instance:

#include "StringChanger.h"

StringChanger change(**this**);  // perhaps default empty constructor here

String globalString = "ThisisGlobal";

void setup(){
    change.changeString(); // perhaps pass reference to **this** here
}
void loop(){}

How can I accomplish this (give a class an object so that it can change some value of that object) in general and not neccesarily in this context.
Errors I currently get:

invalid use of 'this' in non-member function
invalid use of 'this' at top level.

A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.

Your example seems to be trying to make things incredibly complex when they don't need to be.

There are a number of ways of referencing things in one file from another - whether or not they are in a class.  The simplest is to use the extern keyword.  This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."

// Sketch
String myString = "foo";

// Library
extern String myString;
// ... later on ...
myString = "bar";

Of course, that means that the name of the variable is fixed and cannot change.  So you can pass the variable to whatever it is you want to use that variable in.  That could be as simple as passing it to your "changer" function:

// Sketch
String myString = "foo";
StringChanger change;
// ... later ...
change.changeString(myString);

// Library
class StringChanger {
    public:
        void changeString(String &stringToChange) {
            stringToChange = "bar";
        }
};

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:

// Sketch
String myString = "foo";
StringChanger change(myString);
// ... later ...
change.changeString();

// Library
class StringChanger {
    private:
        String *_string;
    public:
        StringChanger(String &string) {
            _string = &string;
        }
        void changeString() {
            *_string = "bar";
        }
}

And there's a myriad of other ways of doing it.


How do you extend the wires from the arduino board to both fsr sensors to be placed on both chairs (one for each) I’m trying to figure out how to extend the wires for both force sensitive resistors so that it could be place on each chair, one sensor on one chair and the other sensor on the other chair

This is how this was originally connected

So what would be the best way to extend both cables to place both sensors on each chair

In ADC sampling there will always be noise.  Longer cables may increase that noise.  Sensors with lower resistance tend have less noise.  For these reasons it would be better to start from a schematic, part numbers and / or specifications rather than a picture.

There are a number of ways to reduce noise.  Hardware solutions include twisted pair and shielded cables.  Software solutions include averaging multiple samples and removing outliers.

If all you are asking is if you can use longer cables, the answer is yes as long as you can tolerate the or compensate for additional noise if any.


What is the difference between a 3 pin and 4 pin ultrasonic range sensor? I am following a tutorial that uses an arduino and ultrasonic range sensor, it calls for a 3 pin module (Paralax 28015-ND) and I have a 4 pin module (http://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf).  The 3 pin seems to have one signal pin (both input and output) and the 4 pin has two separate signal pins (a trigger and echo).  How would I need to change the code and wiring if I am using the 4 pin?  Here is the code from the tutorial:

     /* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe
   modified again 02 Apr 2016
   by Randy Sarafan

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 4;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

It's simple enough... instead of:

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

You would have

pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

(of course you have to define echoPin to be whatever pin you choose to connect ECHO to).

And to save processing time you can have all your pinMode() calls in setup since there is no need to change mode on the fly any more.


Input PUK code, when requested Problem:

I'm working with a GPRS module (the same as in the Arduino GSMShield). In some cases the PUK code is requested, and the PIN is thus locked. For this I wrote some code (which can be seen under "Software"). This code is based on the documentation of "GSM PIN Management". The only problem is that the module is telling us that both the PIN & PUK code is locked. The tutorials, however, does not provide an example how we should resolve this issue from the Arduino itself.

EDIT: When the SIM card is inserted in a smartphone. The PUK code is requested. When the PUK code is provided (and a new PIN) the SIM card is back to normal. But adding the PUK code via the GSM lib. doesn't really work, in contrast to using a smartphone to unlock the PIN code.

Question:

Does anybody have an idea how to resolve this issue? And if it can be done?

Hardware:

Atmega328p
Quectel M95 (as GPRS module)

Software:

PINManager.begin();
int pin_query = PINManager.isPIN();
Serial.print(F("Pin Query is: ")); //output: -2
Serial.println(pin_query);
if(pin_query == -1)
{
  #ifdef DEBUG
    Serial.println(F("PUK is requested"));
  #endif

  if(PINManager.checkPUK(PUK_NUMBER, PIN_NUMBER_CORRECT) == 0)
  {
    PINManager.setPINUsed(true); // I also think this must by "false". Both things were tested, none of them worked.

  }
}

I've resolved the issue by using AT commands instead of the GSM library provided through Arduino.

if(sendGPRSCommand(F("AT+CPIN?"),100).equals("AT+CPIN+CPIN:SIMPUKOK")){
    Serial.println(F("PUK is requested, entering it now"));
    String cmd = "AT+CPIN=\"";
    cmd.concat(PUK_NUMBER);
    cmd.concat("\",\"");
    cmd.concat(PIN_NUMBER);
    cmd.concat("\"");
    sendGPRSCommand(cmd,100);
  }

This code checks if the PUK code is requested, this is the case when the pin_query is -1 or -2 (see question). When the PUK code is requested the new PIN (which is still the same pin as the old one) is given in combination with the PUK code.
The AT commands were found in this manual.


PWM generation for inverter by Arduino Can I generate a PWM signal for a Mosfet driver using a saw tooth wave and sine wave through Arduino ?

Yes you can very easy generate an PWM Output with an Arduino:

void setup()

{

  pinMode(pwmPin, OUTPUT);   // sets the pin as output

}

void loop()

{

  analogWrite(pwmPin, yourWantedValue);  // analogWrite values from 0 to 255

}

  On most Arduino boards (those with the ATmega168 or ATmega328), this
  function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it
  works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8
  only support analogWrite() on pins 9, 10, and 11.

  The Arduino Due supports analogWrite() on pins 2 through 13, plus pins
  DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to
  Analog converters, and act as true analog outputs.

Visit quote origin for more Information.


what to write instead of delay() in interrupt function? I was trying to develop a traffic light signal controller . when the button is pressed, the pedestrian green light will turn on faster than before . I used delay() in Interrupt function, But it is not working as expected . I am totally new in Arduino coding.
My whole code is below:
int carred = 11;
int caryellow = 10;
int cargreen = 9;

int padred = 13;
int padgreen = 12;

int padpushbutton = 3;
int buspushbutton = 2;

void setup(){
  pinMode(carred , OUTPUT);
  pinMode(cargreen , OUTPUT);
  pinMode(caryellow , OUTPUT);

  pinMode(padgreen , OUTPUT);
  pinMode(padred , OUTPUT);

  pinMode(padpushbutton, INPUT_PULLUP);
  pinMode(buspushbutton,INPUT);
  attachInterrupt(digitalPinToInterrupt(padpushbutton), padcontrol,CHANGE);
 attachInterrupt(digitalPinToInterrupt(buspushbutton), buscontrol,CHANGE);
}
void loop()
    {
     carchangeLights();
 }
void carchangeLights(){

   //turn  carred,padgreen off padred high and cargreen on for 10 seconds
  digitalWrite(carred, LOW);
  digitalWrite(caryellow,LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(cargreen, HIGH);
  delay(10000);

   //cargreen off,  turn on caryellow for 4 seconds

  digitalWrite(cargreen, LOW);
  digitalWrite(caryellow, HIGH);
  delay(4000);

   // turn caryellow and padred off,turn on padgreen, turn on carred for 7 seconds
  digitalWrite(caryellow, LOW);
  digitalWrite(padred,LOW);
  digitalWrite(padgreen,HIGH);
  digitalWrite(carred, HIGH);
  delay(7000);
  //turn padgreen off and padred high , caryellow high for 3 second
  digitalWrite(padgreen, LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(caryellow, HIGH);
  delay(3000);

}

void padcontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(2000);
    digitalWrite(padred, LOW);
    digitalWrite(padgreen, HIGH);
    delay(15000);
     }

  else if(yellow == HIGH && red == LOW){
     digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(caryellow,LOW);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
   else{
    digitalWrite(cargreen,LOW);
    digitalWrite(caryellow,HIGH);
    delay(3000);

    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
    delay(15000);
   }

}

void buscontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(3000);
    digitalWrite(carred,LOW);
    digitalWrite(padgreen, LOW);
    digitalWrite(padred, HIGH);
    digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen, HIGH);
    delay(10000);

     }

  else if(yellow == HIGH && red == LOW) {
    digitalWrite(padgreen,LOW);
    digitalWrite(padred,HIGH);
   digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen,HIGH);
      delay(10000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(carred,LOW);
    digitalWrite(caryellow,LOW);

    digitalWrite(padgreen,LOW);
       digitalWrite(padred,LOW);
     digitalWrite(cargreen, HIGH);
      delay(10000);
    }
   else{
    digitalWrite(padred,HIGH);
    digitalWrite(cargreen,LOW);
    delay(10000);

   }
}

what to write instead of dely() in interrupt function?

Nothing. An interrupt service routine (ISR) should not do any things, that take long. That will block any other things from happening, for example Serial communication (which is done by interrupts in the background).
delay() does not work in an ISR, because it relies on the millis() counter to increment. But that is done in another ISR. While one ISR is running, no other can run at the same time. Thus delay() waits forever, that the millis() counter increments.
What to do instead?
Instead you should only use the ISR to set a simple flag variable, for example of type boolean (because it should be a single byte type). Then in your main code (meaning inside loop()) you check for this flag. When it is set by the ISR, you execute the corresponding code and reset the flag. Be sure to declare the flag variable as volatile, so that the compiler knows, that is can change at any time.

That said, you should really ditch all the delay() calls. Instead use a non-blocking coding style involving millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE. There are tons of tutorials and explanations about that on the web and this site. Just search for it. Using a non-blocking coding style is needed, if you want the code to be responsive while doing long timed things.
Also you should look into Finite State Machines (FSM). Thats a very powerful principle, that will come in useful. It fits exactly on a traffic light project. I have once wrote a longer explanation about FSMs in my answer to this question, though you can also google something like "Arduino fsm". You basically divide the behavior of the project into individual states. The current state is hold by a variable. By changing that variable you transition between states. For example padcontrol() could change the state variable to the state for the pedestrian light. I strongly suggest, that you learn that principle to structure your code. I can attest, that it is really helpful.


Is it possible to read extended ASCII from the serial port? My project requires that Serial.read() be able to accept extended ASCII characters (0x80 <=> 0xFF). For example, I would expect reading the character ¥ to yield the decimal value 157. Instead, the read() command has two successful reads, with the values: 194 and 165. Of course, I could create a lookup table and convert, but this is not a viable option. I am conforming to the Grbl standard protocol, which uses these single-byte extended ASCII characters as interrupts. Such a two-byte structure precludes a simple peek/read approach necessitated by the protocol.
Edit I tried to simplify the question for this context, but failed to account for the fact that the Arduino IDE will send the input as Unicode. Regardless, it still does not work when sending bytes directly. Namely, if I send the byte 0x93 via C# as Serial.Write("\u0093"), the Arduino's Serial.read() does not see any bytes available. Sending normal ASCII, e.g., Serial.Write("\u0018"), works fine.

Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.
Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.
If you want to use the Grbl protocol, send interrupts as bytes, do not
think about them as “characters”.


5 switches, 5 leds, 5 tones, in an Array The idea is when a switch is pushed, the corresponding tone will be played as well as lighting up the corresponding LED. I have the circuit set up to where each array matches another, for example Switch one will play tone 1 and light LED 1. When the switch is released the LED turns off and the tone no longer plays.

However I have to use an Array for the sketch instead of declaring each individual switch, led, and tone.  My issue is when I compile the code, I get the error message "i" is not declared.  Not sure where my error is within the for loop in the setup portion of the sketch.

I tried following the example from the Exploring Arduino web page but it did not help.

#define NOTE_C   262 //HZ
#define NOTE_D   294 //HZ
#define NOTE_E   330 //HZ
#define NOTE_G   392 //HZ
#define NOTE_A   440 //HZ

const int SPEAKER = 9;   //speaker on pin 10
int LED[5] = {13, 12, 11, 10, 8};   //led pins
int ledcount = 5;
int buttonState;
int buttonState1;
int buttonState2;
int buttonState3;
int buttonState4;

//Button Array
int Buttons[5]= {3, 4, 5, 6, 7};
int ButtonCount = 5;
const int numButtons = sizeof(Buttons) / sizeof (Buttons[0]);

//Tone Note Array
int Notes[5] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

void setup()
{
  for (int i = 0; i < sizeof (Buttons) / sizeof(Buttons[0]); i++){
  pinMode(Buttons[], INPUT);
}
  for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
  pinMode(LED[], OUTPUT);
}
  for (int i = 0; i < numButtons; i++){
  pinMode(Buttons[i], INPUT);
  debouncer[i].attach(Buttons[i]);
  debouncer[i].interval(100);
}
  buttonState = digitalRead(Buttons[0]);
  buttonState1 = digitalRead(Buttons[1]);
  buttonState2 = digitalRead(Buttons[2]);
  buttonState3 = digitalRead(Buttons[3]);
  buttonState4 = digitalRead(Buttons[4]);
}

void loop()
{

  if (buttonState == HIGH)
  { tone(SPEAKER, Notes[0]);
  digitalWrite(LED[0], HIGH);
  }
  else if (buttonState1 == HIGH)
  {tone(SPEAKER, Notes[1]);
  digitalWrite(LED[1], HIGH);
 }
  else if (buttonState2 == HIGH)
  {tone(SPEAKER, Notes[2]);
  digitalWrite(LED[2], HIGH);
 }
  else if (buttonState3 == HIGH)
  {tone(SPEAKER, Notes[3]);
  digitalWrite(LED[3], HIGH);
 }
  else if (buttonState4 == HIGH)
  {tone(SPEAKER, Notes[4]);
   digitalWrite(LED[4], HIGH);
 }

  else
 {
  digitalWrite(LED[5], LOW);
  noTone(SPEAKER);
 }
}

You have a rogue ; here:

  for (int i = 0; i < sizeof (LED) / sizeof (LED[0]); i++);{
  pinMode(LED[], OUTPUT);                                 ^------HERE
}

That is terminating the for, making it empty, and the following block is a completely different scope.

Another thing I spotted - you aren't putting i into your array index LED[] (should be LED[i]).  The same is true with Buttons[].

However, on a different subject, this:

buttonState == digitalRead(Buttons[0]);
buttonState == digitalRead(Buttons[1]);
buttonState == digitalRead(Buttons[2]);
buttonState == digitalRead(Buttons[3]);
buttonState == digitalRead(Buttons[4]);

is pretty meaningless.  You are comparing values and throwing away the result.

In a similar vein:

if (buttonState = Buttons[0])

stores the current value of Buttons[0] into buttonState and succeeds if Buttons[0] is anything other than 0.  The same goes for all the others.

You need to sort out your comparisons (==) and your assignments (=) and also sort out what you think you are doing with all those buttonStates at the top of loop.


String to equation problem My project is to create a decimal adder via voice recognition. Its like a calculator that only does addition. I am using hc-06 bluetooth module to convert my voice to a string. Let's say for example, I say "21+22" then the lcd would print "21 + 22 = 43". I have no problem in displaying my voice message on the lcd. My problem is that the string can't evaluate the equation. I used toInt() but it only recognizes the first integer. Is there a code to recognize the string and convert numerical values to int separated by + then evaluate it by adding the 2 intergers?

There is no one single function for performing a calculation from a string like you are after in C.

Instead you will have to parse and split your string up into chunks and convert the two numbers into integers (maybe confirming that there is a + between them) and perform the calculation on those two individual integers.


How to add hysteresis to threshold values? This code compares the analog input value against two thresholds, having three voltage regions. Then it will turn on an LED according to what region the read voltage is in.

The problem is that when the voltage read is very close to the threshold, the noise will disturb the output, resulting in an uncontrolled switching between LEDs.

I would need to add some sort of HYSTERESIS around my thresholds to avoid the uncontrolled switching, but I have no idea how to write this into the code language. Would anyone be able to help me writing the threshold bit?

This is the full code:

// these constant won't change:
const int BatteryVoltagePin = 14;   // the pin that battery voltage is attached to
const int GreenLedPin = 3;           // the pin that the green LED (On charge) is attached to
const int OrangeLedPin = 4;          // the pin that the orange LED (no risk) is attached to
const int RedLedPin = 5;             // the pin that the red LED (low battery) is attached to

// Variables will change:
int currentVoltage ;         // current voltage value
int previousVoltage ;     // previous voltage value

void setup() {
  // initialize the battery voltage pin as a input:
  pinMode(BatteryVoltagePin, INPUT);
  // initialize the green LED as an output:
  pinMode(GreenLedPin, OUTPUT);
  // initialize the orange LED as an output:
  pinMode(OrangeLedPin, OUTPUT);
  // initialize the red LED as an output:
  pinMode(RedLedPin, OUTPUT);
}

void loop() {
  // read the voltage across the battery voltage pin:
  currentVoltage = digitalRead(BatteryVoltagePin);

  // compare the current voltage value to its previous value
 if (currentVoltage != previousVoltage)

 delay(10);

    // value above maximum threshold
    {
     if ((( ( analogRead(BatteryVoltagePin) ) > ( 699 ) ))
        {
        digitalWrite(GreenLedPin, HIGH);
        }
        else
        {
          digitalWrite(GreenLedPin, LOW );
        }
    }

    //value between two thresholds (middle region)
    {
     if (( ( ( analogRead(BatteryVoltagePin) ) <= ( 699 ) ) && ( ( analogRead(BatteryVoltagePin) ) >= ( 628 ) ) ))
        {
        digitalWrite(OrangeLedPin, HIGH );
        }
        else
        {
          digitalWrite(OrangeLedPin, LOW );
        }
    }

    // value below minimum threshold
    {
     if (( ( analogRead(BatteryVoltagePin) ) < ( 628 ) ))
        {
        digitalWrite(RedLedPin, HIGH);
        }
        else
        {
          digitalWrite(RedLedPin, LOW );
        }
     }

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
 }

Adding hysteresis behavior to your code is not difficult. You just need to store the state you're in and make the thresholds for transitioning into another state dependent on that.

You can use an enum to store the state:

enum BatteryStates {
  Red, Orange, Green
};

Then, instead of defining and checking against one threshold value, define two thresholds for each transition, separated by so much that you don't observe the undesired flip-flopping behavior.

For example, when transitioning from Green to Orange you could do something like this:

if ((state == Green) && (battery < 690))
  state = Orange;

And the other direction would use a slightly higher threshold

if ((state == Orange) && (battery > 700))
  state = Green;

so that small fluctuations of the voltage do not cause flip-flopping.

(Note that my code assumes

int battery = analogRead(BatteryVoltagePin);

The variable state should be declared and initialized like so:

enum BatteryStates state = Green;

Instead of an enum you could use a simple int and map each state to a number (e.g. red = 1, orange = 2, green = 3), but using enum makes the code easier to read and write. (In fact enum does use integer numbers.)

I might also use a switch statement instead of an if chain to implement the transitions, but that's a matter of taste.)


PWM fans causing temp sensor erroneus values (interference?) I am learning Arduino programming and my current project for real use is to connect 10-17 PC chassis PWM fans to be temperature controlled by the arduino.

So, I have connected the fans exactly as in the picture.
Taken from https://www.racedepartment.com/threads/easy-diy-wind-simulator-for-assetto-corsa.133999/

The temperature sensor is a TMP36 (included in the official Arduino beginner's kit). It is connected to +5V and GND on the Arduino Uno R3. Middle pin is the output and is connected to A0 on the Uno.

Temperature readings seem to work well up until the point the fans start spinning. When they do, the output pin on the TMP36 sensor outputs junk values. Such as 0V or 700mV and it fluctuates up and down if I try probing it with a multimeter. When fans some to a stop however, the output once again stabilizes to a fairly correct value.

I am no expert in electronics interference, but electric motors I suppose cause some electrical noise? I had hoped that PC Chassis fans would already have electric components inside the hub to prevent such though...
Currently I am trying to run 2 fans at the same time but I wish to use 10-17 later once this works.

The fans I am using are Arctic 92mm PWM Rev 02.

I have checked the datasheet (https://www.arduino.cc/en/uploads/Main/TemperatureSensor.pdf) for TMP36 (TO-92 package type) and tried adding a ceramic 0.1µF capacitor between +5V and GND and also add resistor of varying values to the output pin. I believe I got some stabilization out of it but not  enough. Especially when the fans start spinnig faster than 20% duty cycle on pwm it starts to flip out.

I have tried to disconnect power to fans to check if PWM signal may cause it too, but this is not the case as the TMP36 remain stable with PWM on but fans disconnected.

Can someone please help me with explaining what is probably going on and how I can mitigate the problem in a preferably easy way? Do I need to add diodes, capacitors, resistors? Where? Or should I change to a different temperature sensor (which)?

Thankful for help!

In case anyone has the same problem, I solved it. Turns out is was a bad PSU. Buying a new, higher quality one made everything work. So the issue was high ripple I suspect, or at least high enough when applying some load (which is why I noticed that things got worse after the fans started spinning at greater than 20% duty cycle) for the temperature sensor to flip out.


In a circuit with a switch and a pull-down resistor, why does the high impedance of the input not discourage current from flowing into pin? I'm a beginner to Arduino and circuits. I've spent the last couple hours hung up on the concept of how current flows through switches and pull-down resistors, having read every thread and watched every YouTube video I could find on the subject.

I understand that pull-down (and pull-up) resistors are necessary in order to prevent pins from floating. What confuses me is that, if the input pins effectively have a built-in 100 megohm resistance (according to this page), then how is it that a 10k ohm pull-down resistor is enough to dissuade current from flowing directly into ground even when the switch is closed?

Here is a diagram of my circuit:

Am I conflating the high-impedance state of input pins with resistance more generally?

Would really appreciate any clarification on this. Thanks!

Yes, all of the current that flows goes through that resistor to ground.  That way almost all the voltage drops across that one resistor and you are able to read the voltage with the pin on the high side of it.  Only a very very small amount of current flows into the pin when you read a voltage.  It just needs to charge up a very small capacitor.


Arduino Saint Smart Chapter 7 Tri Color Module I am very new to Arduino, I bought a starter's kit and I am working with the user manual that is available. I am in chapter 6 Tri Color Module

I am using the following code:

// Defining the LED driver pins and some other
// variables.
const int numLEDs = 3;

int blueLEDPin  = 3;
int greenLEDPin = 4;
int redLEDPin   = 5;
int ledPin[3];
int ledPinIndex = 0;

// the setup routine runs once when you press reset:
void setup() {

  Serial.begin(9600);

  // initialize the digital pin as an output.
  ledPin[0] = blueLEDPin;
  ledPin[1] = greenLEDPin;
  ledPin[2] = redLEDPin;

  for (int i=0; i < numLEDs; i++)
     pinMode(i, OUTPUT);

}

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

  digitalWrite(ledPin[ledPinIndex%numLEDs], HIGH);
  delay(1000);
  Serial.println(ledPinIndex%numLEDs);
  delay(2000);
  digitalWrite(ledPin[ledPinIndex%numLEDs], LOW);

  ledPinIndex++;
}

My problem is that in the setup() method where the following code is

for (int i=0; i < numLEDs; i++)
         pinMode(i, OUTPUT);

From my understanding pinMode OUTPUT is use to send power out of the specific pin. As the code displays pin 3, 4, and 5 are used but the above code is setting pinMode for 0, 1, 2. Is this write? And even if I comment out the two lines up my project no differently as to the previous code.

Can someone verify if the above code is correct, or should it be setting pinMode for 3, 4, and 5.

This line pinMode(i, OUTPUT); should probably be replaced by pinMode(ledPin[i], OUTPUT);
Otherwise it won't make sense.


Purpose of capacitors in this project I'm currently working on a project where I am making a wheeled robot using the Hack-e-bot library on the arduino. The circuit board which I have planned to put together through soldering will eventually look similar to this:

Here is a schematic:

I understand my circuit quite well but my mentor recommended using a capacitor for this and although I have got it on my schematic, I've never actually worked with capacitors before. Why should they be used in this project?

A capacitor is a device that can store (and release) charge. It is made up of 2 metallic electrodes (or plates) that are separated by a thin dielectric material.

  When you apply a voltage over the two plates, an electric field is created. Positive charge will collect on one plate and negative charge on the other. - build-electronic-circuits.com

In short, a capacitor lets the AC component through and blocks the DC component.

Capacitors can be used in the following ways:

Decoupling Capacitors

(Also called Bypass capacitors)

  A decoupling capacitor’s job is to supress high-frequency noise in power supply signals. They take tiny voltage ripples, which could otherwise be harmful to delicate ICs, out of the voltage supply.

Image reference http://www.seattlerobotics.org/encoder/jun97/basics.html

  In a way, decoupling capacitors act as a very small, local power supply for ICs (almost like an uninterupptable power supply is to computers). If the power supply very temporarily drops its voltage (which is actually pretty common, especially when the circuit it’s powering is constantly switching its load requirements), a decoupling capacitor can briefly supply power at the correct voltage. This is why these capacitors are also called bypass caps; they can temporarily act as a power source, bypassing the power supply.

  Decoupling capacitors connect between the power source (5V, 3.3V, etc.) and ground. It’s not uncommon to use two or more different-valued, even different types of capacitors to bypass the power supply, because some capacitor values will be better than others at filtering out certain frequencies of noise.
  - sparkfun.com

Power Supply Filtering

DC power supplies can be quite noisy on their own. Take the output of a bridge rectifier for example, there is a lot of ripple on the output. Capacitors are a perfect solution for reducing the ripple/noise of power supplies.

Image Reference: http://www.electronics-tutorials.ws/diode/diode_6.html

  Capacitors are stubborn components, they’ll always try to resist sudden changes in voltage. The filter capacitor will charge up as the rectified voltage increases. When the rectified voltage coming into the cap starts its rapid decline, the capacitor will access its bank of stored energy, and it’ll discharge very slowly, supplying energy to the load. The capacitor shouldn’t fully discharge before the input rectified signal starts to increase again, recharging the cap. This dance plays out many times a second, over-and-over as long as the power supply is in use.

Also see Keelan's answer over at electronics stack exchange.

Signal Filtering

  You can also combine capacitors and resistors to form filters that target specific frequencies. - build-electronic-circuits.com

  They can block out low-frequency or DC signal-components while allowing higher frequencies to pass right through. They’re like a bouncer at a very exclusive club for high frequencies only. - sparkfun.com

  For example in an audio system you can target the high frequencies to remove them (e.g. in a sub-woofer). This is called a low-pass filter.  - build-electronic-circuits.com

Image Reference: Wikipedia

Back to your application.

Motors are notoriously noisy. Your mentor has recommended a capacitor to decouple the noise of the motors and protect the IC from voltage drops/spikes.

Side note: D1 in your schematic is a power indication LED. It needs a current limiting resistor in series with the LED to limit the current and prevent the LED from burning out.

Resources:

https://learn.sparkfun.com/tutorials/capacitors
https://www.build-electronic-circuits.com/how-does-a-capacitor-work/
Basic Circuits - Bypass Capacitors
wikipedia.org/wiki/Capacitor
wikipedia.org/wiki/Decoupling_capacitor
Youtube - How a Capacitor Works - by Dr. Oliver Winn
explainthatstuff.com/capacitors


neopixel not blinking I have some neopixels, and I have one hooked up to my teensy.
I want to have the color change, when the push button is pressed vs not pressed. The LED will change colour when I upload the code, if I have the button pressed, green, if the button is not pressed, red.

The serial monitor reports changing button press statuses, so I'm not sure why the neopixel isn't changing.

The adafruit website is confusing to me, they have wonderful and involved project examples, but they never have just a basic IO example.

I would appreciate it, if someone could point out where Im going wrong with this code:

#include <Adafruit_NeoPixel.h>

#define PIN            0

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      1

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
const int buttonPin = 2;
int buttonState = 0;

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(0,OUTPUT);
  Serial.begin(9600);
  pixels.begin(); // This initializes the NeoPixel library.

}

void loop() {

buttonState = digitalRead(buttonPin);
Serial.println(buttonState);

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
      if (buttonState == LOW) {
          pixels.setPixelColor(PIN, pixels.Color(0,33,0)); // green
          pixels.show();

      }else{
          pixels.setPixelColor(PIN, pixels.Color(66,0,0)); // red
          pixels.show();
        }
        delay(500);
  }

this code compiles, without errors, and uploads just fine, but pressing the button won't change the LED color.

I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.


What options do I have to get 5v on my current project? I'm very new to arduino and have started work on my first project, a simple little web server. I'm using a NodeMCU with an sd card module and screen. The issue is that in order to power my sd card module, I need to input 5V which the MCU doesn't provide.

In order to work around this I'm simply using an arduino nano as a power supply to pass into the vin input on the mcu.

What options do I have to exclude the need for the nano? Is there a simple module I can buy that acts as a power supply for 5v?

Any help would be great, thanks!

SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:

3.3V <--> 5V <--> 3.3V

  in order to power my sd card module, I need to input 5V

Which SD card module? Maybe you don't need a "module".


How to Sort a String with Number by Ascending I have trouble figuring out how to sort a String that has a Number in it.

The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.

I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.

edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.

I guess it would also be enough to just sort the strings, but i cant find a function for that also.

As Michel Keijzers points out, qsort is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

parse the start of the strings as integers
compare the integers
if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is atoi(). Unlike
functions like strtol(), atoi() does no error checking, but it is
good enough if you know for sure that the strings have the right format.

Here is the comparison function:

int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}

And here is an example on how to use it:

#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").


TFMini Sensors with Arduino I have three TFMini sensors I need all of them to detect. I only got one to work , pins 4,5 . My info in coding is basic . I really appreciate your help . Thanks in advance.
I think the problem is with Library I can't add TFMini_1.
Here is my code,
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfmini;
TFMini tfmini1;

//Declaring variables and constants
TFMini TFFront;
TFMini TFRight;
TFMini TFLeft;
SoftwareSerial SerialTFMini (4,5);    //(RX, TX)
SoftwareSerial SerialTFMini_1 (6,7);    //(RX, TX)
SoftwareSerial SerialTFMini_2(8,9);     //(RX, TX)

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if(SerialTFMini.available())

  {
    // Serial.println( "tfmini serial available" );
    rx[i] = SerialTFMini.read();

    if(rx[0] != 0x59) {
      i = 0;
    } else if(i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if(i == 8) {
      for(j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if(rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else
    {
      i++;
    }
  }
}

       //Threshold distance in "cm"; speak only when any object is nearer than this distance

void setup()
{

  //Initializing Baud Rates
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  SerialTFMini.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
tfmini.begin(&SerialTFMini);
}

void loop()
{
   int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while(!distance) {
    getTFminiData(&distance, &strength);
    if(distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
   }

delay(100);

}

First: Why are you including, declaring and initializing the library's tfmini object, if you then don't use it for reading the sensor?
Your problem will be, that you can only listen to exactly 1 SoftwareSerial interface at a time. If you listen to the first interface and the sensor on the second interface is sending something, you will miss that data.
I suggest, you switch the Uno for a board with more hardware Serial interfaces (which work via hardware, thus can work in parallel). The Arduino Mega for example has a total of 4 hardware Serial interfaces.
Though you might get away with the Uno when working with the external trigger mode. The TFMini library has an example named SingleReading. It sets the SingleScanMode in setup(). Then it issues an external trigger and then reads the sensor. I suggest trying the following: In your code you initiate all 3 TFMini objects with their respective SoftwareSerial object. Then in loop() you go through these 3 items, first calling listen() on the corresponding SoftwareSerial object. Then you issue the external trigger on the corresponding TFMini object and read the data from it. Then you go to the next SoftwareSerial interface and call listen() on it, and so on. The idea is, that with an external trigger you can control, when you will get a valid data frame. I'm not sure, if the sensor will also send some data between the triggers, but that data should just be discarded without any problem.
Note: I cannot test this idea, because I don't have the corresponding hardware. You will have to test that yourself.


Can I send data from one MKR1000 to another MKR1000 I want to simply send data from one MKR1000 to the other over wifi, both are connected to the same network, but sending the data is where I get stuck, I've looked through tuts everywhere but can't seem to find an answer.. can someone point me to a solution?

I've set up my devices using the tut https://www.arduino.cc/en/Tutorial/Wifi101WiFiChatServer
but the devices don't communicate to each other they only take telnet from the host server(my laptops wifi hotspot)

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


Library to correct time for DST I am using a Uno as a data logger with a DS1307 RTC and the following libraries Time.h DS1307RTC.h

The DS1307 does not have any support for DST and neither library includes Time Zone.

Are there any libraries which adjust for DST?

I used the Timezone module to correct my times for DST.
It took a little time to sort it out, so I though I would post the steps I followed.

Customise WriteRules for my Timezone.
I copied rule from WorldClock.
NOTE also need to modify Timezone in setup(void)
Run WriteRules.pde to write rules to EEPROM address 100

Run TimeRTCSet.pde to set RTC time to UTC.
Start Serial Monitor.
In Terminal send time to Arduino

date -u +T%s > /dev/tty.usbmodemFA131

Run HardwareRTC.pde to demonstrate time display in UTC & local

I modified my sketch by including the following code:-

#include <Timezone.h>    //https://github.com/JChristensen/Timezone
⋯
Timezone myTZ(100);       //assumes rules stored at EEPROM address 100
TimeChangeRule *tcr;        //pointer to the time change rule, use to get TZ abbrev
time_t utc, local;
⋯
utc = now();
local = myTZ.toLocal(utc, &tcr);