text:
7 Segments display with arduino mega2560
I doing a small project with 6 display 7 segment (I will call A1, A2, A3, A4, A5, A6) and 3 cd4543B (I will call Da, Db, Dc) with an arduino mega 2560. I also use 6 transistor to control power supply of display.
Da is use for A1, A2
Db is use for A3, A4
Dc is use for A5, A6
The circuit is done, and work if I use only 4 display I have tried different combination (A1, A2, A3, A4, or A1, A2, A5, A6 or A2, A3, A4, A5, or A3, A4, A5, A6) and all work well.
but If I want to use five or six display, nothing work....

there is resistance for each segment of each display which not appear on the diagram.
my code for 5 display :
//Da
const int bit_A=8;
const int bit_B=9;
const int bit_C=10;
const int bit_D=11;
//Db
const int bit_E=22;
const int bit_F=24;
const int bit_G=26;
const int bit_H=28;
//Dc
const int bit_I=40;
const int bit_J=42;
const int bit_K=44;
const int bit_L=46;

// transistors
const int alim_dizainemillier= 3;
const int alim_millier=4;
const int alim_centaine=5;
const int alim_dizaine=6;
const int alim_unite=7;

void setup()
{

pinMode(bit_A,OUTPUT);
pinMode(bit_B,OUTPUT);
pinMode(bit_C,OUTPUT);
pinMode(bit_D,OUTPUT);
pinMode(bit_E,OUTPUT);
pinMode(bit_F,OUTPUT);
pinMode(bit_G,OUTPUT);
pinMode(bit_H,OUTPUT);
pinMode(bit_I,OUTPUT);
pinMode(bit_J,OUTPUT);
pinMode(bit_K,OUTPUT);
pinMode(bit_L,OUTPUT);
pinMode(alim_dizainemillier,OUTPUT);
pinMode(alim_millier,OUTPUT);
pinMode(alim_centaine,OUTPUT);
pinMode(alim_dizaine,OUTPUT);
pinMode(alim_unite,OUTPUT);

digitalWrite(bit_A,LOW);
digitalWrite(bit_B,LOW);
digitalWrite(bit_C,LOW);
digitalWrite(bit_D,LOW);
digitalWrite(bit_E,LOW);
digitalWrite(bit_F,LOW);
digitalWrite(bit_G,LOW);
digitalWrite(bit_H,LOW);
digitalWrite(bit_I,LOW);
digitalWrite(bit_J,LOW);
digitalWrite(bit_K,LOW);
digitalWrite(bit_L,LOW);
digitalWrite(alim_dizainemillier,LOW);
digitalWrite(alim_millier,LOW);
digitalWrite(alim_centaine,LOW);
digitalWrite(alim_dizaine,LOW);
digitalWrite(alim_unite,LOW);
}

void loop()
{
 for(int i=0;i<100000;i++)
 {
   afficher_nombre(i);

 }
}

void afficher_nombre(int nombre)

{
 long temps;
 int unite=0,dizaine=0,centaine=0, millier=0, dizainemillier=0;
 dizainemillier=nombre/10000;
 millier=(nombre-(10000*dizainemillier))/1000;
 centaine=(nombre-1000*millier)-(10000+dizainemillier)/100;
 dizaine=(nombre-(centaine*100)-(millier*1000)-(dizainemillier*10000))/10;
 unite=nombre-(dizainemillier*10000)-(millier*1000)-(centaine*100)-(dizaine*10);

 temps=millis();
 while((millis()-temps)<500){

    digitalWrite(alim_dizainemillier,HIGH);
    afficher_CD(dizainemillier);
    digitalWrite(alim_millier,LOW);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    delay(5);

    digitalWrite(alim_dizainemillier,LOW);
    digitalWrite(alim_millier,HIGH);
    afficher_CM(millier);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,HIGH);
   afficher_CM(centaine);
   digitalWrite(alim_dizaine,LOW);
   digitalWrite(alim_unite,LOW);
   delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,LOW);
   digitalWrite(alim_dizaine,HIGH);
   afficher_UD(dizaine);
   digitalWrite(alim_unite,LOW);
   delay(5);

   digitalWrite(alim_dizainemillier,LOW);
   digitalWrite(alim_millier,LOW);
   digitalWrite(alim_centaine,LOW);
   digitalWrite(alim_dizaine,LOW);
   digitalWrite(alim_unite,HIGH);
   afficher_UD(unite);
   delay(5);
 }
}

void afficher_UD(int chiffre)
{
  digitalWrite(bit_A,LOW);
  digitalWrite(bit_B,LOW);
  digitalWrite(bit_C,LOW);
  digitalWrite(bit_D,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_D,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_C,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_B,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_A,HIGH);
           chiffre=chiffre-1;
         }
}

void afficher_CM(int chiffre)
{
  digitalWrite(bit_E,LOW);
  digitalWrite(bit_F,LOW);
  digitalWrite(bit_G,LOW);
  digitalWrite(bit_H,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_H,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_G,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_F,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_E,HIGH);
           chiffre=chiffre-1;
         }
}

void afficher_CD(int chiffre)
{
  digitalWrite(bit_I,LOW);
  digitalWrite(bit_J,LOW);
  digitalWrite(bit_K,LOW);
  digitalWrite(bit_L,LOW);

      if(chiffre>=8)
         {
           digitalWrite(bit_L,HIGH);
           chiffre=chiffre-8;
         }
     if(chiffre>=4)
         {
           digitalWrite(bit_K,HIGH);
           chiffre=chiffre-4;
         }
    if(chiffre>=2)
         {
           digitalWrite(bit_J,HIGH);
           chiffre=chiffre-2;
         }
    if(chiffre>=1)
         {
           digitalWrite(bit_I,HIGH);
           chiffre=chiffre-1;
         }
}

I don't understand why it's not working. Could it be a power supply problem ? even if there is never two display used at the same time (delay between them, see code)
Thanks a lot for any help.

Try this link Arduino and CD4543
To control a common cathode seven segment display using CD4543
PH ( Pin 6 ) should be set LOW.
LD ( Pin 1 ) should be set HIGH.
BL ( Pin 7 ) should be set LOW.

Try this code for each segment, could be faulty segment too :)
int Ph  = 6;      //arduino pin connected to the Ph pin of 4543
int BL  = 5;     //arduino pin connected to the BL pin of 4543
int LD  = 11;   //arduino pin connected to the LD pin of 4543

int A   = 7;
int B   = 9;
int C   = 10;
int D   = 8;

void setup()
{
    // Declare all the pins as OUTPUT pins

  pinMode(Ph,  OUTPUT);
  pinMode(BL,  OUTPUT);
  pinMode(LD, OUTPUT);

  pinMode(A , OUTPUT);
  pinMode(B  , OUTPUT);
  pinMode(C  , OUTPUT);
  pinMode(D, OUTPUT);

}

void loop()
{

    // Display 0

  digitalWrite(Ph,  LOW);
  digitalWrite(BL,  LOW);
  digitalWrite(LD,  HIGH);

  digitalWrite(A , LOW);
  digitalWrite(B , LOW);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 1

  digitalWrite(A , HIGH);
  digitalWrite(B , LOW);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 2

  digitalWrite(A , LOW);
  digitalWrite(B , HIGH);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 3

  digitalWrite(A , HIGH);
  digitalWrite(B , HIGH);
  digitalWrite(C , LOW);
  digitalWrite(D , LOW);

  delay(1000);

    // Display 4

  digitalWrite(A , LOW);
  digitalWrite(B , LOW);
  digitalWrite(C , HIGH);
  digitalWrite(D , LOW);

  delay(1000);
}

This 3 pin on the CD4543 are already well linked... I have done a better post with video of my problem : https://arduino.stackexchange.com/questions/38374/7-segment-displays-arduino-mega-2560

The circuit is done,

unnecessarily complex: you can share the data lines among the drivers.


text:
Arduino Uno: Receive MIDI data from DAW
I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)
I would be happy using a Serial>Midi of some sort if it's the only way, but true USB MIDI would be nice.

What kind of MIDI interface hardware does your PC have? And what exactly is your question?

I would like to do it over USB. And my question is what would be the best and most appropriate way to do this, I could be sending 50-200 notes a second so needs to be relatively fast

Which Arduino are you using?

Arduino Uno R3.

So you want to make a sound to light machine eh? Is there any detail in the midi messages that is particularly important for triggering the LEDs?

Potentially ON velocity for colour in the future, but other than that, just note number.

The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.
On AVRs, you typically use the Lightweight USB Framework for AVRs (LUFA), which has support code for both the basic USB protocol and for USB MIDI.

I'm kind of new to some of this, how would I go about using that?

LUFA has lots of examples.

For USB Midi you could use: Arduino UNO + USB Host Shield + USBH_MIDI Library
The library is specifically for the USB Host Shield. I've used this to take MIDI over USB from a digital piano and used it to control some LEDs. It's pretty strait forward to get it all working.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
LEDs effects changing with a button
So I have a bunch of functions (methods) made and I want to make it so that if the button is clicked (single click) the effects to change... I thought something like:
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH) {
  counter++;
  if(counter>2) {
    counter=0;
   }
 }
if(counter==0) {
  Foo1();
}
if(counter==1) {
  Foo2();
}
if(counter==2) {
  Foo3();
}

But I noticed that it will only read the input button(buttonPin) if I click the button in the exact time (when the function has already ended and at digitalRead time)... So is there some way to do it even if the function is in progress to cancel it and go to the other ones (some way that the digitalRead will read it non stop)?

Not if you your functions use the delay() function as part of the animations. We would need to see your entire program in order to recommend improvements.

A short button press last ~100 milliseconds or more. If loop() take less than that to run (worst case scenario), you will always catch the button.

I think you want to look at interrupts.  You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed.  If you foos take a long time to execute the you will miss button presses.
What you can do is use 'interrupts'.  Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things).  For instance they can change the value of a global volatile variable.  Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).
With you current code, you would remove the digital read line, and the if (buttonState == HIGH) block and move those into you ISR.  This would mean every click would be counted.  If you wanted the ISR to stop the current foo and move on then you foos would need to check a flag that the ISR also set and when they see it they return.
In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work.  Keep it fast and small.
https://www.arduino.cc/en/Reference/AttachInterrupt
https://www.arduino.cc/en/Reference/DetachInterrupt

I had been timing single click as part of a minimal button debouncer (wich is part of a larger project).
According to my tests, the duration of button press is as follow:

Quick fire press. Average, 40-70 ms per button press.
Normal quick. Average, 150 ms per button press.
Long press. Over 400 ms (very personal).

Now, if you loop takes less that 40 ms, your sketch still can catch almost any button press. If you restrict to "normal" button presses, your loop can take up to 150 ms without trouble.
So, profile your app. Measure your worst case scenario and the take action.
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Donald Knuth

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is there a Serial write buffer limit and does the Arduino reset if it is hit?
I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.
Update:
Having eliminated all code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.
So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.
Note: The flash of TX no longer shows up with the empty sketch.

Show us your code.

When you detach the serial monitor do you also remove the USB cable and power it from a different power source, or does it remain connected to the computer?

It remains attached to the USB power of the computer, though in service it is designed to run on the Vin pin or 9V DC jack

What is the power consumption of the additional GPS module? It may be off limits for arduino power supp.

The GPS module draws 25 mA and I am pulling from the 5 V supply. The module is designed to take 3.0 - 5.5 V supply.

Not that it turned out to be relevant, but the answer to the original question is that Arduino serial output calls block until there is room in the buffer.

It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:
void setup() {}

void loop() {}

the board would still periodically reset itself.
I eliminated:

flushing the receive buffers,
eliminating all receives by disconnecting pins,
speeding up/slowing down the serial port/s,
speeding up/slowing down the GPS reporting rate,
auxiliary hardware,
code,
includes,
defines,
laptop power supply noise,
board revision in Arduino IDE,
Arduino IDE version,
USB port on laptop,
trying this hack to prevent the RESET pin from going low,
another Mega 2560 and a Due

None of the above influenced the issue.
The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.
Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.

It is probably not the Arduino IDE but some other rogue piece of software, like a GSM modem manager (a modern Arduino sort of looks like one) or a driver for old serial mice.  Having the Serial monitor open likely means that the serial device is claimed and unavailable to the undesired program.

Is that in any way an indicator of nefarious software running, or just annoying? I imagine something in the HP Workstation special tools could be trying to do that.


text:
Arduino/Genuino 101 5 volts pin
Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.
What's it for?

That is just a regulated 5V and it is 5 tolerant.

What does a regulated input means? And why can I use it without damaging the pins?

Regulated input refers to regulated power input. And The board operating voltage and I/O is 3.3V but all pins are protected against 5V overvoltage So, that doesn't means you will want to power the board with 5V.

In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.
However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.

fwiw, i've never seen an unregulated 5v psu output...

yes, otherwise how could you get a constant voltage.

Oh, my misconception was that because of the sign of the voltage (positive) I was assuming it to be an input pin, in the sense voltage would go to, and not from, there. Thanks for the help


text:
Run program from SRAM on SAMD21?
I am looking for an example of how to load a program from sd card to SRAM and execute it from there on the SAMD21.
I understand that the given MCU use the Von Neumann architecture and all code is privileged.

According to an important Wikipedia article, “Neuman's surname is often misspelled as "Newman"”.  I guess the same thing happens to  Von Neumann.

BTW, per Table 22.11 in Joseph Yiu's  “Guide to ARM Cortex-M0 and Cortex-M0+ Processors” book, the Cortex-M0 and -M0+ use Von Neumann architecture, while the Cortex-M1, M3, M4, M7 use Harvard.  The SAMD21 is a Cortex-M0+ processor, so Von Neumann as stated in question.

@JamesWaldby-jwpat7 By the way, the proper pronunciation of Neumann is actually Noiman. It's German.

@Majenko, of course that's true of Von Neumann's name, as he was born and raised in Germany; but perhaps less so of Neuman's name, which is from whole cloth.  Anyhow, artificer has corrected the spelling in the question.

@JamesWaldby-jwpat7 Yeah, the proper pronunciation of Neuman is "Chumly".

There's two aspects to what you want to do - one (relatively) easy, and one (comparatively) hard.
The first thing you will need is some way of getting your program into RAM. That would mean some software running on the chip that will accept the program and place it into RAM then execute it. You will have to write your own bootloader-like program that runs in Flash that will perform the task.
The second, harder, thing is to compile your program in such a way that it will execute from RAM. And that's no easy task.
Ideally you want to compile the code as position independent code (with the command line flag -fPIC), but that depends on the compiler being able to do that for this chip. If not, you will have to compile it so that the code expects to reside in RAM with all addresses used for jumps, etc, going to the right location. And that brings me to the second aspect of compiling, the linker script.
If you have your code in RAM you can't also have your variables in the same place in RAM. You will have to subdivide the RAM into two sections - the code execution section and the variable storage section. This is done through the construction of a custom linker script which is used during the linking phase of compilation. It tells the compiler where in memory to place everything - code, variables, etc. You will need to craft your own linker script to divide the RAM up in a suitable manner to give you enough room for your code while at the same time not starving it of variable storage space. This will also make sure all jumps, etc, in your code use the right addresses in case you can't (or don't want to) use -fPIC.
So, given all that, do you still really want to execute code from RAM?

Thanks a lot for the linker warning. I will have to consider the SRAM size constraints.

After a lot of reading I found an ATMEL document about the subject. They already created the linke script!  the document is named "AT07347: Executing Code from RAM"


text:
Why doesn't analogWrite() work
Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.
    class Pwm
{
  unsigned long previousMillis = 0;
  unsigned long currentMillis;
  int LED;
  int DELAY;
  int up;
  int down;
  int x;

  public:
  Pwm(int led, int Delay) {

    int LED = led;
    pinMode(LED, OUTPUT);

    DELAY = Delay;
    up = 1;
    down = 0;
    x = 0;

  }

  void Update() {
    currentMillis = millis();
    if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 0) {
      up = 1;
      down = 0;
    }
   }
  }

};

// create Flasher Objects
Flasher red(12, 1000, 250);
//Flasher yellow(11, 500, 500);
//Flasher green(10, 250, 1000);
//Flasher blue(8, 250, 500);

// create PWM Objects
Pwm pin9(9,8);

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

void loop()
{
  red.Update();
  //yellow.Update();
  //green.Update();
  //blue.Update();
  pin9.Update();
}

if I load this code everything works fine. I only have issues with the OOP method.
int LED = 9;
int DELAY = 8;
int up = 1;
int down = 0;
int x;
unsigned long currentMillis;
unsigned long previousMillis = 0;

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

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    if (x == 0) {
      up = 1;
      down = 0;
    }
  }
}

Does pin 9 on you board support PWM?

Yes the second sketch works just fine and uses the same pin as the first

Ermm... yes...doh

The constructor in your Pwm class declares a local variable LED which it sets equal to the parameter led. You use the member variable LED in other methods, so you probably meant to set the member variable of the same name, not create a local.
Remove the int from before LED = led in the constructor.

So by creating the local variable LED in the constructor the update() method doesnt see pin 9 being set to output? Please correct me if I'm wrong. I can't make changes to my sketch until later. I will let you know how it turns out.

@beewrangler Yes that's correct.  C++ lets you declare two variables with the same name at different 'scopes' (some compilers warn you).  Put simply scope is between the braces {}, you know of global variables and then function variables, they are two examples of scope.  You have define LED as a class member (class scope) and then LED as a function variable (function scope).  The lowest level of scope takes precedence, function level, and when you are outside the constructor, but inside the class (i.e. update()) then the class member is used.  Good spot Mark.

As stated above by Mark Smith I had my LED variable scope wrong. His suggestion has fixed my problem. Thank you


text:
CurieBLE receive data without pairing
I read exist articles about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:
 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
 bluetooth.begin(57600);
 while (!bluetooth.available()) {}
 byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!

what problem are you referring to?

The code above will only read one byte

@dandavis I want to get one byte using BLE without pairing

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

Thank you for the explanation.
So without SPP and detail configurations for BLE I can't receive data from neuro?

Seems like not :(


text:
Communication between Arduino and raspberry Pi
So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino  sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

What is an arudionk?

You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.
The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).
How you arrange those instructions to get it to do things is entirely up to you.


text:
Controlling a LED array from Arduino NANO
I have a project Im currently busy with that I need a lot of help with.
What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).
I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?
How would I manage the current for all the LEDs
Thank for taking the time to listen to a n00b like me :D

i think you can drive them all from one GPIO, depending on the RGBs used; which?

Are you planning on buying a pre-made LED matrix, or making your own? That might affect the advice somewhat. Individually addressable LEDs are available but not (AFAIK) in matrices.

Probably going to buy individual LED and assemble them in a grid myself

In that case, I would suggest looking into addressable LEDs. Get it working once (Arduino libraries exist), no messing with external shift registers.

You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).
For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.
If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.
And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.

There are a lot of ways to do what you want to do. Wiring them up individually would be one possibility those find a chip with that many pins can be a challenge
You can use shift registers, either statically or dynamically.
You can also use display drivers, like 7219 or the ht variants.
...
End of the day it will depend on your application and constraints it has to live under.


text:
How to include userid, pass to WifiClient connect() api
These are my remote server credentials that I want to connect from my local device.
Server  m12.cloudserver.com
User    <myname>
Password    <mypassword>
Port    19999
_ or
api_key 5678909876-009-00d

I want to use the WiFiClient client() API as shown, but where or how do I include the User credentials ? so that I can make a successful connection to the remote server from my device connected over Wifi.
Cut and paste from my Arduino code.
const int httpPort = 19999;
if (!client.connect("m12.cloudserver.com", httpPort)) {
 Serial.println("connection failed");
 return;
}

Read the API docs.

WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named Postman. Postman runs on Chrome browser. Postman can compose such headers for you. Then you can insert them into your arduino code.


text:
How to Sort Elements of Array in Arduino Code?
/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.
lt[6]={35,15,80,2,40,110};

Have you tried man 3 qsort? - Arduino programming is nothing more than C/C++ so you can use almost everything available there. Know your Language!

Simplest, though not most efficient, is a bubble sort. https://en.wikipedia.org/wiki/Bubble_sort

Online version: qsort() manual from avr-libc.

@Kwasmich no i am new in this field, please help me.

I'm voting to close this question as off-topic because it's a programming question.

@EnricBlanco can i not ask any programming question?

Stack Overflow is a much better match for your question than this site.

@EnricBlanco but this site is much active in respond than stack overflow, so i tried this. So i request to open this topic for discussion as it is helpful for me. Thanks

@EdgarBonet , it really helped me. please upvote the question.

As mentioned in the comments, qsort is a good option:
// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
  // Need to cast the void * to int *
  int a = *((int *)cmp1);
  int b = *((int *)cmp2);
  // The comparison
  return a > b ? -1 : (a < b ? 1 : 0);
  // A simpler, probably faster way:
  //return b - a;
}

void setup() {
  // The array
  int lt[6] = {35, 15, 80, 2, 40, 110};
  // Number of items in the array
  int lt_length = sizeof(lt) / sizeof(lt[0]);
  // qsort - last parameter is a function pointer to the sort function
  qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
  // lt is now sorted
}

void loop()
{
}

@Johny Mopp it really helped me.


text:
How to work with arduino softwareserial communication using HC-05?
This is my first project using bluetooth module HC-05.i am using two of this module.one is with arduino nano(slave) and another one is with arduino uno(master).I have paired them through AT commands .
for testing,i was giving a pulse in pin 7 on nano.if there is a pulse,then slave will send character "1".if not then it will send "0".
in UNO there is an LED connected with pin 13.if master receives '1',then LED will on and if recieves '0',LED will remain off.
here is my source code ----------
slave code=>

master code=>

the Arduino IDE isn't showing any bug,but code is not working at all.though,i am giving pulse in pin 7 on NANO, the LED in pin 13 on UNO is remaining off.i am at aloss now.please help me as soon as possible..

Is copy pasting code really that hard?

sorry,I didn't get you.

sorry...the main code has now been attached.

Does CTRL + C and CTRL + V ring a bell?

bro,would you please give me any solution?

Don't put pictures of you code in a post again, makes life very difficult!
The problem is the first line of the slaves loop
loop()
{
    if (slave.available()>0)  // Here is the bug
....

So If the "slave" serial port has data available to read then write data.  The master never writes to the slave so the slave never has any data to write, so your slave never sends any data and your master never reads any data.
In short remove that line and it will work.

sorry,I'm new to this group.so i didn't know the rules.But ,it still is not working,though i have removed the line.now the indication LED on HC-05 is flashing very quickly.

arduino RX=>TX of hc-05 and arduino TX=>RX of hc-06 ........this connections are same for both master and slave...for your convenience i have added these information.

at last,fixed it

What fixed it?  If it was this please mark this as the answer to help others, if not answer the question yourself.


text:
ESP 8266-01 Library
I've just bought two of these wifi modules in the hope of setting up some sort of sensor network. Please could somebody recommend a good library for the arduino.
Cheers

Program it direct. If you must use an Arduino with it then use the Arduino as a programmable IO expander.

if you want to program the ESP itself - https://github.com/esp8266/Arduino

You don't need a library.  At the most basic level you fire AT command to it via a serial connection, but that's like using a Ferrari to go grocery shopping once a week.
It has a 80/160MHz processor 10 digital and one analog port (although you got the version where only one digital port is exposed).  You can program it through the Arduino IDE (You need to go to the board manager to download the BSP for it).  Then like Majenko says, it should be talking to the Arduino (over I2C or SPI) and treating the Arduino is the GPIO expander.

the esp01 has 3.5 GPIOs exposed, not just 1; you can drive an rgb led with one...

Thanks @dandavis i always thought the 01/07/12 meant the number of gpios exposed.


text:
Array Addressing
Is it possible to use a name instead of a number to address an array? I was reading about enum lists and thought it might be possible.
ie
int array[3] = {something, somethingElse, somethingMore]
array[second] => somethingElse
I am asking as I have an array looking after flags for several functions and would like to be able to use the function name instead of a number to address the array.
bool flag[6] = {1, 1, 1, 1, 1, 0}; // Power, Jump 3, Jump 7, Fade 3, Fade 7, Pause active

I'm voting to close this question as off-topic because it's a generic programming question.

No, but you can use a struct:
struct flags {
    uint8_t power;
    uint8_t jump3;
    uint8_t jump7;
    .... etc ....
};

struct flags myFlags;

myFlags.power = 1;
if (myFlags.jump3) {
    .... stuff ....
}

Or you can continue to use a simple numeric array and assign names to the numbers, either with #define, const variables, or an enum.
enum flags {
    power, jump3, jump7, fade, fade7, pause
};

bool flag[6] = {1, 1, 1, 1, 1, 0};

flag[power] = 1;
if (flag[jump3]) {
    .... whatever ....
}

That's brilliant thanks, ill give them a go.

Used the struct method, works perfectly :) thanks


text:
Triggering Sound - Arduino + Contact Mic
I previously created a sound installation using contact mics and computer (ableton+max msp) where sound would be triggered when people touched/tapped on the object/surface. Now I want to do something similar but want to get rid of the computer as it will be at a night club space where people will be walking around so I don't want to leave the computer there.
What I exactly want to do is to be able to load some sounds into arduino and again use contact mic on the object and when people touch it, the sound will be triggered. I know it won't be as creative as doing it with ableton where there is live-editing possibility but I'm happy with one type of sound in this one. I can probably find some codes here and there but I'm not sure what I exactly need to use to be able to do this.
I have few uno boards and lots of other bits that I've collected but haven't used before, so I would be very happy if you could help me as a novice.
Thank you

I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much.
It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier,  but if you're using little ones like 8ohm 0.25W with the music shield will be enough

some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground

If you're asking what kind of sensor you'll need, look for capacitive sensors or there's even this instructable that could be implemented with a conductive material (see link below).
You can definitely do this project without a computer, you just need to figure out the following things:
1) Power consumption - How much current will your Arduino, speaker, sensors, etc use? Calculate your "mAh" from this and determine what kind of battery (my recommendation) will fit your needs.
2) Housing for the arduino+circuitry. If you're doing this in a nightclub you want this to be waterproof/somewhat durable.
3) SD card shield/adapter to store the sounds you want.
I have lots of experience as a hobbyist so please do not hesitate to ask for more questions. Good luck!!
Link to instructable: https://www.instructables.com/id/DIY-Touch-Sensor/


text:
Variable was not declared in this scope
When I compile this code I get a  error: 'currentState' was not declared in this scope.
The code:
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 }

state currentState; <---- Error

const int BUTTONPIN = 4;
const int ROTARYPIN = A0;

void setup()
{
  //Open Serial Monitor for debugging purposes
  Serial.begin(9600);

  //Configure the pins
  pinMode(BUTTONPIN, INPUT);
  pinMode(ROTARYPIN, INPUT);

  //Initialise the LCD
  lcd.begin(16, 2);

  //Assume that the current state is wait for start up signal

  currentState=WAITSTARTUP;
}

You have missing semicolon after the enum:
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 };  // <-- here

//go the Tools > Boards and check that you have selected the right option of your hardware? your remaining code is almost ok. But remember to add semicolon ";" sign at end every coding line.
  enum state: int{NOTREADY,WAITSTARTUP,WAITSECRET,REVEALSECRET};
  state currentState; //<---- Error

  const int BUTTONPIN = 4;
  const int ROTARYPIN = A0;

  void setup()
  {
    //Open Serial Monitor for debugging purposes
    Serial.begin(9600);

    //Configure the pins
    pinMode(BUTTONPIN, INPUT);
    pinMode(ROTARYPIN, INPUT);

    //Initialise the LCD
    lcd.begin(16, 2);

    //Assume that the current state is wait for start up signal

    currentState=WAITSTARTUP;
  }

I don't see what has board selection to do with this problem. And the solution to the actual problem was already posted.


text:
unexpected primary-expression before ';' token
I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :
include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.
What am I doing wrong???

Use myservo instead of servo in the blocks (to start with :).

include #include<Servo.h> looks a bit screwy to me... ;)

You are looking at the last compiler error, but the first one is the most important. You can scroll up in that output window to find the first compiler error. Are you using Arduino IDE 1.8.2 with an Arduino Uno ? because I get a different compiler error.

1) You should be using:
myservo.write(pos);

instead of
servo.write(pos);

for all of your  methods.
2) Change:
include #include<Servo.h>

to
#include <Servo.h>

This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)
*Verify that your board will work, I know Mega, Uno and Nano will function properly.
P.s. Here is the whole code in correct format:
#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop()
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}

I got it working on a NANO without the stacked parenthesis. My problem was I was trying to use an external servo library (not needed) and my USB cable was no good (power only)

@CSnyder okay! Glad to hear it ran on Nano, I will correct my answer, and overall that you got your project working. Good luck!


text:
error: 'analogRead' was not declared in this scope
I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:
#include <Stepper.h>

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;  // number of steps the motor has taken

void setup() {
}

void loop()
{
    int sensorReading = analogRead(A0); //ERROR

    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

    if (motorSpeed > 0)
    {
        myStepper.setSpeed(motorSpeed);
        myStepper.step(stepsPerRevolution / 100);
    }
}

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.

Did you follow the rest of the process to integrate the Arduino environment into Codeblocks?

@IgnacioVazquez-Abrams Do you have a link to this process?

did you try to include "Arduino.h"?

Did you get this issue fixed? If so, could you post an answer as to how you fixed it?

Also, which version of codeblocks?

// yours code looks Ok, but i think problem is with Arduio IDE setting. Go to the "Tool > Boards...." in arduino IDE and make it sure that you have selected the right option of Arduino module. Mean it is same as you are using in hardware?

He is using Codeblocks IDE with Arduino core, not the actual Arduino IDE.


text:
Uno - measure the voltage, NOT connecting GND
I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).
The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.
Is there any way to measure the Voltage over the resistor without using GND?

If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .

Thank you! Yes you got the question right. Nice idea specifically since I can't afford to add more circuitry. And True, The Resistor's "GND" doesn't need to level with the GND of the rest of the circuit. I'll implement soon and provide feedback

It turns out that by attaching two ADC channels to the ends of the resistor, I don't get a valid or even stable result. The result is a chaotic number. Any suggestions?

@MakanTayebi, Do you print all 3 values? (Ie, both analogs & their difference)?  If not, printing them all might indicate if variation at one end is causing the problem.  Or might indicate wrong pin being read.  Note, if you use the same ref voltage for both readings, subtract the two readings before scaling instead of after

I print both and both fluctuate, so much that their difference is not also meaningful. And that's even before scaling. But what about the Refererence Voltage? What PIN would that be?

The AREF pin can be used to input a reference voltage of 1 V or more, which can be selected for use via analogReference(EXTERNAL) (see link).  By default, analogReference(DEFAULT) is in effect, and it selects +5 V on a 5 V board, or 3.3 V on a 3.3 V board.  For most-stable results on Unos/Nanos, use analogReference(INTERNAL) if a 1.1 V max reading is acceptable.

I just tried it and it works great

Why you are using AD0 pin for analog read? use A0-A7 for Arduino mega and A0- A5 for arduino uno case for reading of analog values. For more detail study the voltage devider and you will understand the problem more easily. As i understand there is no need to use ground.

I don't get why this answer has gotten negative reps. I'll try taking the GND out of the loop.

“There is no need to use ground” is untrue.  Yes, voltages are differences in potential between points, neither of which need be ground.  But when you measure voltages using an Arduino ADC, some ground-reference point in the circuit under test should connect to the Arduino's ADC ground (which, on Mega, Uno, Nano, is wired to digital ground...)

And what do you think AD0 refers to in this context?


text:
ST7735 display with esp32
I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit_ST7735.h file. which are as follows.

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.
I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?

Because you're using bitbanged SPI...?

Is copy pasting code really that hard?

The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.
The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.
The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.
If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.

Even with bitbanged SPI, the ESP32 should be do better than the Mega regarding screen refresh rates, that is assuming OP's ESP32 has a much higher clock frequency than 16 MHz, as befits it.

@TisteAndii And assuming there aren't specific length delays used in the bit banging, which would remain the same regardless of clock speed.

I checked. There are no delays. https://github.com/adafruit/Adafruit-ST7735-Library/blob/master/Adafruit_ST7735.cpp#L90

The mega uses hardware SPI which will be faster than bit banging. Bit bang on a fast CPU and you get similar speed to hardware SPI on a mega.

If the OP is in fact comparing ESP32 bit-banging with Mega hardware SPI (default speed DIV4 = 4 MHz), then you'd be right. It seems the fastest toggle speed possible on the ESP32 is 10 MHz, and that's when writing to the CPU registers directly to get fairly optimized assembly. https://www.esp32.com/viewtopic.php?t=1595


text:
Conversion of Arrays into Matrix?
I'm going through problem in Arduino code. I have three Arrays and want to convert them into a matrix. I have tried hard but couldn't solve issue.
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float Loadbase,Loadshift;

void setup() {
    for (int i=0;i<24;i++){
        Loadbase={lb1[i],lb2[i],lb3[i]};
    }
}

void main() {
}

Why don't you use two dimensional array directly? Anyway, Loadbase is not an array. The == is equality operator. You should start with some C++ tutorial.

@KIIV i know the logic how arrays are converted to matrix in Matlab. But Arduino coding is bit different than matlab. please give me some example to solve this issue.

I'm not sure what do you want to archieve exactly. I can try to answer it..

@KIIV i want to get a matrix of (3*24) from three arrays.

Google "c multidimensional array".

This is your third general programming question (not specific to Arduino) and the third time we've told you this is off-topic. Don't you care about the site rules?

I'm voting to close this question as off-topic because this is a generic programming problem totally unrelated to Arduino.

Two dimensional arrays in C++ (directly):
float matrix[3][24] = {
    {1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730},
    {1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450},
    {500,500,600,600, 380.3005 ,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250}
};

Two dimensional array indirectly (array of pointers):
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

If you want two dimensional array with copies of lb1/lb2/lb3:
float matrix[3][24];
for (int i = 0; i < 24; ++i) {
    matrix[0][i] = lb1[i];
    matrix[1][i] = lb2[i];
    matrix[2][i] = lb3[i];
}

Btw: you were saying something about "mistakes" if I split definition on more lines, but guess what:
float lb3[24]={500,500,600,600,  380.3005  ,3155. This is a valid float number, but you have only 23 items then.
If you use at least space as a number separator, it can't be even compiled:
float lb3[24] = { 500, 500, 600, 600, 380. 3005, 3155, 530, 400,  400, 600, 350, 250, 250, 500, 500, 250, 1655, 1655, 3155, 2130, 250, 150, 250};

I need this type of stuff, i am giving you material from your answer. but is not working. and giving error."Error compiling for board Arduino/Genuino Mega or Mega 2560".  float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

@HafeezAhmadFiiZue  My code is tested. However your code pasted here is full of extra characters (and those are invisible in Arduino IDE) that can't be compiled. Some kind of zero width spaces.

in next comment i will paste the code please check it once again,  for arduino mege 2560 in arduino IDE. it is giving error,"Error compiling for board Arduino/Genuino Mega or Mega 2560".

float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

Please do not post code in comments. If you need to post code please edit your question and use a proper code block (indent it 4 spaces).

Check this code with slight amendments:
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};

void setup() {
int loadbase[3][24] = {{lb1}, {lb2}, {lb3}};
void main()
{}


text:
How to Read Voltage Level?
I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.
volts = analogRead(A3);    // read the input pin
Serial.println(volts)

Show where and how in your code you declare volts, and how are you wiring the voltage you want to read to the analog input.

Also, in what way is this not working?

Other than missing the semicolon on the end of the second line, this chunk of code will work. Can you please show your whole program?

Note that instead of printing out the number of volts on the input, it will output an ADC count that stands for some number of volts; by default, 1024/5 counts per volt.

//use this syntax and add ; sign at end of each line and try to read voltage level via voltage divider circuit.
volts = analogRead(A3);    // read the input pin
Serial.println(volts);             // debug value

First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.
float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!

Your first solution will always be 0. 5 / 1024 does integer division which always results in 0. Any number multiplied with 0 is then 0.

@gre_gor I stand corrected! Good catch. I completely forgot about that. :)


text:
Communicating between two arduino terminal using Xbee
I have 2 Arduinos, mounted with Xbee Shield and Xbee S1 module on each.
One arduino is mounted on car chassis while another is connected with PC. Our AIM is to send signal from the arduino connected on PC and the motor will be controlled by the Arduino connected on car chassis.
Here is the code of the arduino connected with PC:
char msg= "";
void setup(){
 Serial.begin(9600);}

void loop(){
 msg=Serial.read();
 serial.println(msg);
}

Here is the code of the Arduino on car chassis:
char msg = ' ';
int motorA1 = 2;
int motorA2 = 3;
int motorB1 = 4;
int motorB2 =5;

void setup() {
  pinMode(motorA1, OUTPUT);
  pinMode(motorA2, OUTPUT);
  pinMode(motorB1, OUTPUT);
  pinMode(motorB2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  while(Serial.available()>0){
  msg=Serial.read();
  switch(msg){
   case 'f':Serial.println("Forward");break;
   case 'b':Serial.println("Backward");break;
   case 'r':Serial.println("Right");break;
   case 'l':Serial.println("Left");break;
   case 's':Serial.println("Stop");break;
 }
if(msg=='f'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  Serial.println("Running Forward");
  }
if(msg=='b'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,HIGH);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,HIGH);
  }
if(msg=='s'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='r'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='l'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  }
}
}

Now our next AIM is to send back a feedback from car to the Arduino terminal of PC, e.g. if we are giving 'f' as a input and we get a reply 'Running Forward' on the next line. What line of code should we incorporate for that?

Isn't your code doing that already in the switch statement?

You need two serial connections on the pc Arduino. One that connects via xbee and one that connects to the pc/usb monitor. You need to describe what hardware you have because it can be complicated if you are using a shield with fixed serial pin assignments.

//your code looks almost ok. The thing that i am feeling wrong is that arduino at the PC end. It should communicate with PC and 2nd arduino at the same time. So use arduino mega or "#include " library to avail extra Serial at this end if you are using arduin uno. Your code will be like this..
char msg= "";

void setup(){
Serial.begin(9600);
Serial1.begin(9600)//<----error
}

void loop(){
 msg=Serial.read();
 serial1.println(msg);//<- - -error
}

Please tell me how to add extra serial on the arduino at PC using software serial library as I have UNO. please provide me the final code


text:
If Else Alternative
I've written a function that heavily relies on the If / Else statement but I feel it's a very beginner way to achieve functionality. Are there any better ways to achieve the same functionality?
Code:
void jumpThree() // Update from left then right
{
  if (effectCounter[0] < tiles) // Right, first tile
  {
    Serial << flag[6] << "\t";
    Serial << newRed[0] << " " << newGreen[0] << " " << newBlue[0] << "\t";

    if (flag[6] == 1)
    {
      oldRed[0]   = (tileBuffer[effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[effectCounter[0]] & 0x0000ff);

      Serial << effectCounter[0] << "\t";
    }

    else if (flag[6] == 0)
    {
      oldRed[0]   = (tileBuffer[6 - effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[6 - effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[6 - effectCounter[0]] & 0x0000ff);

      Serial << (6 - effectCounter[0]) << "\t";
    }

    Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

    if ((newRed[0] - oldRed[0] != 0) || (newGreen[0] - oldGreen[0] != 0) || (newBlue[0] - oldBlue[0] != 0))
    {
      // Red difference
      if (newRed[0] - oldRed[0] > 0) // Positive red change
      {
        oldRed[0] ++;
      }
      else if (newRed[0] - oldRed[0] < 0) // Negative red change
      {
        oldRed[0] --;
      }

      // Green difference
      if (newGreen[0] - oldGreen[0] > 0) // Positive green change
      {
        oldGreen[0] ++;
      }
      else if (newGreen[0] - oldGreen[0] < 0) // Negative green change
      {
        oldGreen[0] --;
      }

      // Blue difference
      if (newBlue[0] - oldBlue[0] > 0) // Positive blue change
      {
        oldBlue[0] ++;
      }
      else if (newBlue[0] - oldBlue[0] < 0) // Negative blue change
      {
        oldBlue[0] --;
      }

      if (flag[6] == 1)
      {
        tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      else if (flag[6] == 0)
      {
        tileBuffer[6 - effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      // tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
    }

    else if (((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0))
    {
      effectCounter[0] ++;  // Go to next tile
      //flag[1] = false;
    }
  }

  else
  {
    flag[1] = false;
    effectCounter[0] = 0;

    if (flag[6] == 1) // Flip flop between left and right updates
    {
      flag[6] = 0;
    }

    else if (flag[6] == 0)
    {
      flag[6] = 1;
    }
  }
  delay(wait);
}

Hopefully oldX and newX are signed, otherwise you will never get into if(newRed[0] - oldRed[0] < 0) as it is always false if one of both is unsigned.

They're not signed but it does work correctly, any idea why?

This question might belong over at [codereview.se].

If-else is just fine. However, the function might become more readable if you split the code into multiple separate functions.

For part of this you can use the switch case style
Which looks like
switch(flag[6]) {
    case 0  //your code here
             break;       // and exits the switch
    case 1 : cout << '2';
             break;
    default: //all other cases
}

There is also the ? syntax that can help

condition ? result_if_true : result_if_false

If I "refactor" this type of code (really we all get there from time to time) I try to go back to "what I want". From What I understand your code would look like (no code validation this is a educational example)
int bufferoffset=0;
int bufferMultiplyer=1;

if(flag[6] == 0)
{
   bufferoffset=6;
   bufferMultiplyer=-1;
}
oldRed[0]   = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0xff0000) >> 16;
oldGreen[0] = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x00ff00) >> 8;
oldBlue[0]  = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x0000ff);

Serial << (bufferoffset+bufferMultiplyer*effectCounter[0]) << "\t";

Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

int redDiff=newRed[0] - oldRed[0];
int greenDiff=newGreen[0] - oldGreen[0] ;
int blueDiff=newBlue[0] - oldBlue[0] ;
if(redDiff!= 0)
{
  redDiff > 0?         oldRed[0] ++:   oldRed[0] --;
 }
if(greenDiff!= 0)
{
  greenDiff> 0?         oldGreen[0] ++:   oldGreen[0] --;
 }
if(blueDiff!= 0)
{
  blueDiff> 0?         oldBlue[0] ++:   oldBlue[0] --;
 }

    tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
}

for more details on switch case see http://en.cppreference.com/w/cpp/language/switch
for more detail on ? syntax https://stackoverflow.com/questions/795286/what-does-do-in-c

if(greenDiff!= 0) == if(greenDiff)

I personally don't like if(greendiff) because greendiff is not a boolean. I consider that style.

No, if-else is really the simplest way of dealing with that.
If you wanted to abstract it a little since you have repeated code just with separate variables, you could make a little function
// Note: set the right parameter variable types here
// to match your unspecified variables.
static inline int testUpDown(int a, int b) {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}

// Inside your flag tests:
oldRed[0] = testUpDown(newRed[0], oldRed[0]);
oldGreen[0] = testUpDown(newGreen[0], oldGreen[0]);
oldBlue[0] = testUpDown(newBlue[0], oldBlue[0]);

If you wanted an inline conditional variant you could do it with this:
oldRed[0] = ((newRed[0]-oldRed[0]) ? ((newRed[0]-oldRed[0])/abs(newRed[0]-oldRed[0])) : 0);

But who can understand that?  You could always macro it:
#define UPDOWN(A,B) (((A)-(B)) ? (((A)-(B)) / abs((A)-(B))) : 0

oldRed[0] = UPDOWN(newRed[0], oldRed[0]);

you can shorten a lot of the vertical space with more compact conditionals, including ternaries to remove double conditionals where one result must follow from another.
For example, you can turn this:
  // Green difference
  if(newGreen[0] - oldGreen[0] > 0)  // Positive green change
  {
    oldGreen[0] ++;
  }
  else if(newGreen[0] - oldGreen[0] < 0) // Negative green change
  {
    oldGreen[0] --;
  }

into just this:
// Green difference
int gDiff = newGreen[0] - oldGreen[0];
if(gDiff) oldGreen[0]+= (gDiff > 0) ?  1 : -1;

//when there are multiple if/if-else/nested if/nested if condition then obviously it creates complexity in the code. I think switch is best option to use in such conditions. plz check switch condition if it is feasible in your program. Moreover i will check it in detail if it still not works. Try.........

@Matt please elaborate the objective of your code?


text:
Understanding schematics: resistors attached to Attiny85 pins V-USB
I'm currently trying to create my own Attiny85 usb thumb(to mimic an joystick). I understand that I have to limit the voltage on the attiny's pins that are connected to the D+/- pins from the usb. In various schematics there are some pull-up resistors used with some zener diodes(that will drop the voltage that exceeds 3.3 V).(taken from insidegadgets)
Question:
#1
I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid an regulator?(as other schematics incorporate in them)
#2
Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.
#3
An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.007=171 ohms.That resistor attached to the attiny would produce a 1.2 drop).
#4
There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

While 1.2/0.7 ~ 1.71, 7 mA is not 0.7 amps but 0.007, giving 171Ω rather than 1.71.  Also, please edit your question and provide an attribution for the schematic.  I'm wondering why the zeners are on the USB side of the 68Ω resistors instead of on the '85 side.

@JamesWaldby-jwpat7 The zeners are on the USB side so the current from the GPIO pin is limited before being sunk through a zener. You don't want to overload the current from the GPIO pins, do you?

@Majenko, ok, I see that now

I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid the regulator?

If you have a 5v supply, as in a USB connection, and you want to run off 5v, then you do not need any regulator.

Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

Because only that pin needs pulling up to indicate the presence of a device on the USB bus.

An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.7=1.71 ohms).

You can only use a resistor to drop a fixed voltage of you have a fixed current. The current you quote is the chip's supply current, not the GPIO current, which you cannot know or predict. Also, if you did use a resistor it would operate both ways and the 3.3V coming in would also be reduced so the MCU will not be able to read the data.
Even if you did know the current you would find it was very small so a huge resistor would be needed, which would induce intolerable amounts of noise. It would also violate the USB specifications.

There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

They are to protect the ATTiny's IO pins. Without those the zener diodes will sink way too much current from the IO pins and damage them. They also act partially as termination resistors for the USB bus (which should be 20Ω).

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Different data showing in arduino serial and hyperterminal
I've connected to RS232 device with arduino. When showing data in arduino its showing as:
235
157
191
157
159
153
157
0

While in Hyperterminal it's showing as:
 101 102 103 104

How to get the same data as hyperterminal in arduino too?
My Arduino code:
   if (RS232.available()) {
    int incomingByte = RS232.read();

    Serial.println(incomingByte);

    //Sending to bluetooth
    BTserial.println(incomingByte);
  }

The Arduino serial monitor is incredibly crude and barely usable at the best of times. It may be to do with line endings, or something similar. Personally I would use putty or teraterm rather than hyperterminal, since that is a bit crude too (though not as crude as the arduino serial monitor).

@Majenko In my case, Hyperterminal is showing correct data as above. But serial should show similar data too. Is there any problem in my Arduino code?

Not in that little snippet, no. However the two serial programs do deal with line endings in a very different manner, which is probably where the difference in displays lies.

What results do you get if you change int incomingByte to char incomingByte or to byte incomingByte?

@JamesWaldby-jwpat7 on changing to "char incomingByte" special chars print, somewhat like square symbol. And on changing to "byte incomingByte" result remains the same.

Rahul Rastogi, by  “result remains the same” do you mean the same as for "char incomingByte", or like the “int incomingByte” output?


text:
Why is my Analog Input channel adding voltage to my signal?
EDIT: Here are the links to the sensor spec sheet (http://www.omega.com/temperature/pdf/HX71.pdf) and manual (http://www.omega.com/Manuals/manualpdf/M4543.pdf) for your reference.
I'm using a relative humidity (RH) sensor with an Arduino Mega. The RH sensor runs off of +/- 24V  (which is being sourced by a power supply), and outputs a signal from 0-5VDC. Naturally, I am plugging this output signal into my A0 channel. There is a bare Earth Ground wire that is wired to the power supply's earth ground (possible error?) Arduino's GND is connected to the power supply's EARTH GND, fyi.
I compared the voltage reading in my Arduino Serial Monitor to a reliable Fluke multimeter, and the analog input channel is adding ~.2 Volts!
From some research, I have read about "high impedance" "source impedance" "internal wiring of Arduino" etc, but unfortunately I am failing to grasp the reason why this is happening. I'd like to know so then I could figure out a solution on my own.
Below is a schematic of what I'm dealing with so that it may better illustrate my issue (also my code). Thank you for your time, and I appreciate your help!
)
void setup()
{

Serial.begin(9600);

}

void loop()
 {

  float hs1 = ((( analogRead(A0) * ( 5.0 / 1024.0) ) )* 20.0 );

  Serial.print("RH%");
  Serial.print(":");
  Serial.print(hs1);
  Serial.print(";");
  Serial.println();
  delay(1000);

}

Link to the RH sensor data sheet?

Oh yes! here's the spec sheet: http://www.omega.com/temperature/pdf/HX71.pdf and the manual http://www.omega.com/Manuals/manualpdf/M4543.pdf

I'm using model HX71-V1, thank you @Majenko

One of the biggest mistakes people make when calculating the voltage of an ADC is they assume the chip is running at 5.000000 volts. Have you measured the 5V pin of the Arduino with your Fluke?

How do you know your fluke is accurate ? :). You could measure the 5v using A1 and 'calibrate' your reading on the fly.

Wow, you guys are gonna get a KICK out of this!
The analog input channel was not adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).
I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.
Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.
Thank you everyone for your help!


text:
Can removing lines of code destroy a motor driver and make it catch fire?
I am making a pid line follower robot. So I was tinkering with code to optimize my line follower when i removed two lines of code unknowingly. As soon as I uploaded my code and started the line follower, 4 mosfets on my motor driver smoked and burst into blue flames. Bought a new one and same outcome. Interestingly, The ones corresponding to the left motor alone had this outcome as I removed " return Motorspeed1" and " return MotorSpeed2" from the function corresponding to the left motor. Heres the code :
signed int MotorSpeed = 70;
int MotorSpeed1, MotorSpeed2;
int MotorFunc(signed int a, signed int b){
   if(a >= -10 && a < 0)
   {
      b = -b;
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, LOW);
      MotorSpeed1 = MotorSpeed + b;
      MotorSpeed2 = MotorSpeed + b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed2 = constrain(MotorSpeed2, 0, 255);
      analogWrite(_pwm_m1, MotorSpeed1);
      analogWrite(_pwm_m1, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }
   if (a < 10 && a > 0)
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, LOW);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2= MotorSpeed+ b;
      MotorSpeed1 = constrain( MotorSpeed1, 0, 255);
      MotorSpeed2= constrain( MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1,  MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

   else
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2 = MotorSpeed - b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed1 = constrain(MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1, MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

}

And i called this function in the code using :
    MotorFunc(a,b)

This code ran just fine, But when i removed the return functions from the first if condition, I destroyed 2 motordrivers,
Is this possible?
Edit:
I am updating the whole code:
The main code tab :
     int _dir_m1 = 2;
     int _pwm_m1 = 3;
     int _brk_m1 = 4;
     int _brk_m2 = 5;
     int _pwm_m2 = 6;
     int _dir_m2 = 7;

     int sen1 = A4;
     int sen2 = A3;
     int sen3 = A2;
     int sen4 = A1;
     int sen5 = A0;
     signed int Error = 0;

     int Kp = 20;
     int Ki = 0;
     int Kd = 0;

     void setup() {
     pinMode(_dir_m1, OUTPUT);
     pinMode(_pwm_m1, OUTPUT);
     pinMode(_brk_m1, OUTPUT);
     pinMode(_dir_m2, OUTPUT);
     pinMode(_pwm_m2, OUTPUT);
     pinMode(_brk_m2, OUTPUT);

     pinMode(sen1, INPUT);
     pinMode(sen2, INPUT);
     pinMode(sen3, INPUT);
     pinMode(sen4, INPUT);
     pinMode(sen5, INPUT);

     }

     void loop(){

     signed int a = Sensors();
     signed int b = PID(a);
     MotorFunc(a,b);
       }

And pretty much it. I am leaving out PID as Its not required along with error selection.
The setup is -
Arduino mega connected to 5 ir sensors
12v 9ah battery
500rpm 12v motors johnsons
and the motor driver 20 amp 20v-30v

Motor driver link with specs

You can't have two return statements after each other. So there is already something very wrong here.

@Gerben I suspect he isn't using those returned values, since they are defined as global variables anyway.

@Gerben I dont know why but the program refuses to work without all those return statements. Any idea how it can burn a mosfet by its absence?

Is it possible that i shorted two motor inputs by not calling return in on all the statements? I didnt call the return statement in all the functions once but that didnt make the driver burn, just that the program wasnt behaving as needed. @Majenko

Without seeing your entire program and knowing all your wiring it's impossible for us to know that kind of thing. Yes, it's possible. Is it what happened? Who knows?

Ok I will update my entire setup @Majenko

It all depends on how the circuit works and how it is controlled.  A basic H-bridge looks like this:

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".
However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.

It isn't possible to say arbitrarily that removing the statements could or could not cause the drivers to burn out. What does the caller do with the value returned by your function? With the return statement removed, the value returned to the caller is unknown. Is there any value which, if returned to the caller, could set the conditions for driver burn-out?

Is it possible that i shorted two motor inputs by not calling return in on all the statements? I didnt call the return statement in all the functions once but that didnt make the driver burn, just that the program wasnt behaving as needed

A function will return if control reaches the end the final '}', even without a return statement.


text:
Issue with PIR sensor
I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.
Because of cost constraints, I decided to go with the low cost HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505 sensor?
Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Would an RC filter across the input help?


text:
Can't cast char to unsigned char?
byte RSV_Resp_test[3] = {'a', 'b', 0};
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

produces the error
error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                      ^

How can this be an ill-formed cast?  I just need to print the value as a ascii character, not as a number.

Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.

This may help shed light on it: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used - summary: static_cast is what you normally want in 99% of situations and is what you need here. reinterpret_cast is only used when you want to do really strange things.

In a bit of standardization weirdness, section 5.2.10 [expr.reinterpret.cast] says only certain kinds of reinterpret casts are allowed!? Maybe it is time to move back to 'C'.

Personally I never use them and just use (char)varname instead.


text:
More speed from ATMEGA328 Internal Clock
I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?
The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

You have to optimize your code, you may can do the shifting out using hardware SPI. Show your code and describe your application.

I have updated the question to include details and the code. There are 20 called to shiftout() in the display loop.

What is this function shiftOut it uses GPIO pins?

Reference here: https://www.arduino.cc/en/Reference/ShiftOut

OK then from the reference "This is a software implementation; see also the SPI library, which provides a hardware implementation that is faster but works only on specific pins". This is what you need.

I saw that, however it only works with some pins. MOSI = 11, MISO = 12, SCK = 13. I do not believe that aligns with my latchPin = 8, clockPin = 12, dataPin = 11. Right?

Ideally improve the efficiency, but you could consider glueing an oscillator on top of the ATmega or somewhere on the PCB to improve your prototype, and then doing a re-spin of the board design when you need a quantity where such re-work is impractical.  Note that there are a lot of ARM MCUs that cost less than an ATmega and can run faster with internal clocks, though they are not through-hole.

@TannerEwing Yes, it does not.

shiftOut() relies on digitalWrite(), which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing shiftOut() using direct port
access instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.
Edit: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being too fast. You may try to play with the delay value.
#include <util/delay.h>

/*
 * Especialized and faster shiftOut().
 * This assumes no one is touching PORTB at the same time.
 *
 * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
 */
void myShiftOut(uint8_t val)
{
    for (uint8_t i = 0; i < 8; i++)  {
        // Send data bit.
        if (val & 0x80)
            PORTB |= _BV(PB3);
        else
            PORTB &= ~_BV(PB3);
        val <<= 1;

        // Toggle clock twice.
        PORTB |= _BV(PB4);
        _delay_us(0.5);
        PORTB &= ~_BV(PB4);
    }
}

When the SPI bus is not possible, then this is the way to do it. Arduino has bitSet() and bitClear macros which result into the same I/O bit instructions. The 'val' should shift the 0x80 to the right. It is not possible to delay "0.5" only unsigned long numbers, and delayMicroseconds() could be used, or the delay by clock cycles (I forgot the name).

@Jot: You wrote: “The 'val' should shift the 0x80 to the right”. Shifting 0x80 to the right works also, although it produces slightly less efficient code, as it requires an extra register to hold the bit mask. Shifting val to the left, with the fixed mask 0x80, allows the compiler to use a bit-test instruction (sbrs) and never store the bit mask. “It is not possible to delay ‘0.5’ only unsigned long numbers”. This is incorrect. Delaying by 0.5 µs (or even 0.125 µs, given an 8 MHz clock) works perfectly well with _delay_us() (not with delayMicroseconds()). Try it!

I'm very sorry, I made two mistakes. You are right. I have tested it in software and _delay_us(0.5) results in a delay of 0.506 µs (according to a software approximation. Thank you. I learned something new.

It is 8MHz and not faster.
The only way to make it faster is to add an external crystal with two capacitors and change a fuse for external clock.
Many ATtiny chips can run at higher frequencies with the internal clock. Do you use a DIP package of the ATmega328(p) ?
Did you optimize the code ? The ATmega328(p) has highly optimized code to change an output pin. At what rate do you want to shift out data ?

The code could be optimized still (maybe). I would need to nearly double execution time of the loop. I have updated the question to include code and additional details about the application.

Double the execution time is easy. A digitalWrite() takes about 5µs and a optimized I/O instruction is 0.125µs, that is 40 times faster.

This is the slow Arduino shiftOut code: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_shift.c

I wrote the following earlier but the moderator deleted:
"
A few things to try.
An external oscillator.
An external rc oscillator.
Optimized code: the code left a lot to be desired.
Optimized hardware: there is no reason you shift out the same value so many times. That's a waste of time.
"
edit: just give you some sense on a 16MIPS ATmega:
1) your code executed in 2.54ms -> a refresh rate of 400Hz;
2) your code software-optimized can be executed in 0.103ms -> a refresh rate of 1Khz;
3) your code both software and hardware optimized can be executed in 0.054ms -> a refresh rate of 2Khz.
what it tells you is that:
1) raising the clock isn't the only way to speed up execution;
2) there is a fundamental limit for this topology on how many shift registers you can drive before it starts to flicker;
3) to drive the most out of your design, you have to pay attention to both software and hardware. that's why embedded engineers get paid a lot of money to do;
BTW, the higher clock rate, the more likely you will run into timing issues in a long chain of shift registers. 20 - 25 shift registers are likely the limit in real life applications.


text:
Attempted to disable autoreset - now the voltage regulator only outputs 4.0v
I followed the guide from the Arduino website, by placing a 10uF capacitor between GND and Reset. However, now the voltage regulator only provides 4v (Vin=13V). It correctly has 5V when being powered via USB.
What happened? Isn't there a 10k resistor between +5V and Reset that should prevent the chip from being overloaded? Or did the Reset pin sink the entire energy of the capacitor?

Is there anything else plugged into the Arduino?

Yes, but there wasn't any problems before. It's been working fine in full-time operation for several months, and all devices are powered by a seperate 7805.

How hot is the onboard LM1117 regulator?

Yes, the LM1117 5.0 is very hot. But I'm not sure if this is because some component, e.g. the ATmega chip, or a capacitor, has failed, and therefore whether it makes sense to try to replace the regulator.

It sounds like the regulator may be going into thermal shutdown. Without the capacitor does it right itself?

I've removed the GND-Reset capacitor even before asking this question, but the problem remains. The other capacitors are SMD mounted and not easy to remove. Perhaps there's no other way than to replace the whole board.

I assume you also tried removing all the other connected devices? Even though they are externally powered they may have a bearing on it.


text:
Program jumps alone from void loop() to another void
//simple alarm system
int RipSensor1 = 12;
int RmkeyA = 3;
int RmkeyB = 5;
int RmkeyC = 6;
//--------------------------------------------------------------------------

void setup()
 {
  Serial.begin(9600);
  pinMode(RipSensor1,INPUT);
  pinMode(RmkeyA,INPUT);
  pinMode(RmkeyB,INPUT);
  pinMode(RmkeyC,INPUT);
  pinMode(13,OUTPUT);
  Serial.println(F("System Is Up & Running")); }
  //----------------------------------------------------------------------

void loop()
 {
  Serial.println(F("Main Loop Start"));
  digitalWrite(13,LOW);   //for debugging
  if (digitalRead(RmkeyA) == HIGH)
   {
    Rip1Status();
   }
 }
//----------------------------------------------------------------------

void AlarmSMS1()
 {
  //send sms to admin1
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Rip1Status();   // return to this void (monitoring)
 }
//----------------------------------------------------------------------

void Rip1Status()
 {
  Serial.println(F("VOID Rip1 Start..."));
  while (digitalRead(RmkeyB) == LOW) //Arm mode
   {
    digitalWrite(13,HIGH);
    if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
     {
      Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
      long RipTimer1 = 0;
      long Rip01 = 0;
      int z = 0;
      int x = 0;
      while (digitalRead(RmkeyC) == LOW)
       {
        RipTimer1++;
        Serial.println(RipTimer1);   //for debugging
        if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
         {
          z = 1;
          Serial.println(F("1st CheckPoint OK"));
         }
        else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
         {
          x = 1;
          AlarmSMS1();
         }
       }
      Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
      RipTimer1 = 0;
      z = 0;
      x = 0;
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      break;
     }
    else Serial.println(F("Monitoring"));  //for debugging
   }
  Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
  Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
  loop();
 }

I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
B Key Pressed --> Disarming
Monitoring Loop ends --> GoTo Main Loop
Main Loop Start
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012.............

Why this happen?
What i am doing wrong?

It's called a function not a void.

loop() calls Rip1Status(), which calls loop(), which calls Rip1Status(), which calls loop(), which calls ....
That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for Rip1Status() to return to the main loop, delete the loop() call at the end of the function. When Rip1Status()exits, control will automatically return toloop()at the statement following theRip1Status()` call.

JRobert. Same thing happen.

Same thing happen with you suggestion. RipTimer1 still count and program not stay on main loop. I try to redirect on other dummy void or break command but same think happen. Something big i missing here

JRobert thank you. After i read what you say many times finally i found the way. I have split Rip1Status() function in two. i have remove call function at the end of AlarmSMS1() and add return command on my code. Now works just fine. Thanks again....


text:
Switching low current AC
What is the simplest way to switch ON/OFF a 60v and 5 mA of current ?
I don't want the common relays for arduinos as they make click noise.

Solid State Relay (SSR)?

e.g., Fotek SSR-10 DA for next to nothing on eBay...

Is there something smaller than SSR ? maybe Triac or similar

That's basically what is inside the SSR. A triac and a bit of control circuitry. BigClive does a teardown of one: https://youtu.be/DxEhxjvifyY

// Following devices could be helpful in you case.

Power BJT as a switch (check datasheets if it comes on your required range).
Solid state relay is obviously, but cast is little high in this case.


text:
Arduino DUE samples per second with the DAC
I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

According to the datasheet:

2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.
Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.
Or, if you don't need a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.

I have never use any arduino board before, if i am rigth, the command to generate a signal  with de DAC is analogwrite, The resolution is not a problem I beleave, do you think that comand can generate those 10 samples per cycle???

I am saying this beacause I need to keep it simple, I do not have time for getting involve with more DMA code :D

With this code, the Arduino DUE was able to generate 250 samples per second approx. I tested it with a signal generator and an oscilloscope. I have found it on this web page http://www.electrosmash.com/pedalshield. All credit is for them.
Here is the code:
// Licensed under a Creative Commons Attribution 3.0 Unported License.
// Based on rcarduino.blogspot.com previous work.
// www.electrosmash.com/pedalshield

int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
int LED = 3;
int FOOTSWITCH = 7;
int TOGGLE = 2;

void setup()
{
  //ADC Configuration
  ADC->ADC_MR |= 0x80;   // DAC in free running mode.
  ADC->ADC_CR=2;         // Starts ADC conversion.
  ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

  //DAC Configuration
  analogWrite(DAC0,0);  // Enables DAC0
  //analogWrite(DAC1,0);  // Enables DAC0
}

void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
  //in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
  //POT0=ADC->ADC_CDR[10];                 // read data from ADC8
  //POT1=ADC->ADC_CDR[11];                 // read data from ADC9
  //POT2=ADC->ADC_CDR[12];                 // read data from ADC10

  //Add volume feature with POT2
  //out_DAC0=map(in_ADC0,0,4095,1,POT2);
  //out_DAC1=map(in_ADC1,0,4095,1,POT2);

  //Write the DACs
  dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
  dacc_write_conversion_data(DACC_INTERFACE, in_ADC0); //write on DAC
  //dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
  //dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
}


text:
How to write arduino code which reads the value of a flex sensor?
Since this is this the first time im doing Arduino, im really confused what the code is to:
write a code which reads the value(nae the value 'flexValue') of a flex sensor connected to analog input AN0.
The value should be a 10-bit integer number having value between 0-1023, inclusive.

https://www.arduino.cc/en/Reference/analogRead

You should call the function analogRead(), and pass the value of A0 into it because you want to read pin A0. For example:
flexVal = analogRead(A0);

The function analogRead() will return a value from 0-1023, just as you require.
When you call this function, the CPU configures the on-board ADC (analog-to-digital converter) to take a reading from pin A0. The ADC on the Arduino has 10-bit resolution, so it will return a value from 0-1023.


text:
SPI communication between two Ethernet Shields (W5100)
I am a newbie to the world of IoT, I want to ask...
Is it possible to connect two Ethernet shields with SPI? And if yes, how can I codes them?
I have reference from http://www.gammon.com.au/spi and I've tried SPI communication between two Arduino Unos send & receive any data type..
Now.. I want to put Ethernet Shields to each Arduino Unos, and I want to make them can communicate via SPI, It's like they can send & receive data type (ping IP address each other). If that scenario can running well, is it possible I can ping Shield one and Shield two?
(without router/switch, for this IoT research I still used local network, each Arduino w/ Shield plug to each laptop via RJ45 & USB port of course)
Topology:
Laptop A <===> Arduino Uno w/ Ethernet Shield <---> Arduino Uno w/ Ethernet Shield <===> Laptop B.

Note:

<===> = RJ45
<---> = Wire jumper (SPI or Pin 13 12 11 10, GND)

Sorry for my bad language, I didn't speak English well..
Can anyone help me?
Thank you,
H.