text:
Control Brushless ESC From Arduino
I am trying to build a quadcopter using an arduino. I Bought 4 30A ESC's from Ebay the link is http://www.ebay.co.uk/itm/4pcs-Brushless-speed-controller-ESC-MultiCopter-KK-Quad-rotor-X-copter-30A-S-/310950293677?pt=LH_DefaultDomain_3&hash=item486614f0ad and a A2212 2200KV motor, im also using a sparkfun arduino uno. I have connected the white (data) servo wire of the ESC to pin 9 of my arduino and the black (ground) servo wire of the ESC to gnd of the arduino. When i connect the battery to the esc i get the 3 beeps because of my 3 cell battery regardless of what code is on the arduino even if the arduino is not present. the code that is on the arduino is.
#include <Servo.h>

Servo motor;

void setup()
{
  Serial.begin(9600);
  motor.attach(0);
}
void loop()
{
  motor.write(100);
}

I'm not sure what is wrong. Can someone please help me.

If you were using an RC radio, what would the arming and/or calibrating process be for those ESC's?

im not sure about the arming process, im also not using a rc radio its being controlled by bluetooth from a phone, So if i need to arm it will need to be by code.

ESC's like these are designed for use with RC radios and have an arming process (like full throttle two seconds, neutral 2 seconds or something) that someone with a radio needs to do so that the motors don't spin up while they are turning everything on. You will need to find the right one for those ESCs and replicate it with your code.

Gone quiet here.. If the ESC gives you 3 beeps then it's alive. Your code does nothing beyond start up & output a steady 100 p.w.m. - it needs to emulate the RC arming process next, likely a high-to-low transition, you should then get a nice warble to tell you it's about to belt off somewhere... try outputting 1024, delay 300, then 0?

You may have the Servo library very helpful. Check out this answer

I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.
The arming sequence through the controller-receiver was like this:

Connect ESC to battery (arduino is connected to signal and ground prior to this)
Wait for 3 beeps
Set the throttle to the lowest possible
Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.
Here is the code:
#include <Servo.h>
#define POT A0

Servo m1;

void setup() {
  m1.attach(6);
  Serial.begin(9600);
  delay(50);
  Serial.println("Serial ready:");
  arm(m1);
}

void loop() {
  int potValue = analogRead(POT);
  int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

  m1.write(s);
  Serial.println(s);
}

void arm(Servo m){
  Serial.print("Arming.");
  m.write(0);
  delay(100);
  m.write(1224); //A value at which the motor starts turning
  delay(2000);
  m.write(1024); //A value at which the motor stands still
  delay(3000);
  Serial.println(" Armed!");
}

You can also see a video of the whole thing in action here: A2212/13T brushless motor on a pivoting arm
EDIT: Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.


text:
I2C LCD displaying weird characters
I have connected an LCD with an I2C backpack to my Arduino Uno but it prints the wrong characters. The weird thing is that it worked fine for a while and when I updated the code (but didn't change anything to do with the LCD) it started displaying the wrong characters. This happened earlier today too. That time, reinstalling the LiquidCrystal library worked, but it doesn't now.
Does anyone know what might be the problem so I can fix it permanently?
The LCD's SDA and SCL are connected to A4 and A5 respectively and I'm running this code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16     chars and 2 line display

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Hello, world!");
}

void loop()
{
    }

and this is what's displayed on the screen:

add a picture of your wiring please!

Is "LiquidCrystal_I2C lcd(0x27,20,4);" that right for this display? It looks like a 16X2 display. Please post a picture of the LCD adapter.

If you look up the ASCII codes for what you sent vs what was displayed, and also look at "Table 4 Correspondence between Character Codes and Character Patterns (ROM Code: A00)" in an HD44780U spec sheet, you will find hexadecimal values like the following.

e 65, V  56
l 6C, ニ C6
o 6F, θ  F2
o 6F, π  F7
r 72, &  26
d 64, B  24
and so forth.

It appears that the high nibble of what you sent is being used as the low nibble of what is displayed, and the low nibble is being used as the high, but with some bits sometimes going wrong.  Note, a space is 0x20, and the reverse of that is 0x02, which would access a character from the character-generator RAM, which will contain random bits and produce a random blob as in your picture.
If your mis-specification of display size (20, 4 vs 16, 2) isn't responsible for the problem, then maybe there is a hardware problem with the backpack you've soldered on to the LCD.  Look at it under a bright light, using a binocular parts-examination microscope if you've got one, and see if there are loose solder particles, extra solder flux, or loose solder connections on that board.  If you have an oscilloscope, check if your I2C signals are clean and have full swing.

I doubt the swapping of nibbles is due to a poor soldering. But +1 for wading through the datasheet to find the link.

Thank you very much @jwpat7 and @brianrho! Strangely, when I reconnected my lcd with this code just now, it randomly worked again. Anyway, I fixed the 20,4 to 16,2 just to be sure and if it starts acting up again I'll have a close look at the backpack.

Thanks, @WoutervanDijke, I had the same issue, just my problem was that I was printing in the loop() without setting cursor to 0,0 position, hence internal LCD memory got corrupted and it started to print random characters. I fixed the code, but it won't help, just after re-connecting 5V power pin,- LCD started to behave as normal. Hence power pin re-connect works as "factory reset" button for LCD. Cool ! You saved my life :-)

I experienced this while using a STM32f429 discovery board,  and I found out there are two reasons that this happens.

when using a fast microcontroller (180 MHz clock),  if you send I2C packet consecutive LCD may not be that fast to understand it and as James said in other post LCD may lose some packet and get confused. To cope with that you have to put a delay between your packet.
If you reset your MCU board while your LCD is writing something without cutting off power, LCD may get first nibble but lose the second 4bit nibble and interprets your initialize data as second nibble data to show on LCD and simply get confused. If LCD had something like software reset it could help but I did not find anything in datasheet. Though I think there is a hardware walkaround

if you could disconnect K in 8050 transistor and connect LCD Ground to that point then you could disconnect and connect LCD power just by toggle P3 pin through PCF8574 IC when you are initializing your LCD.actually you will lose some control over LCD backlight. you can consider R/W pin too because almost all firmware just write on LCD and simply lower this pin. I bring the purpose schematic in below

in Module simply disconnect ground pin from module and LCD and in LCD board connect K pin to ground as i put the image here

in your Code When you are Initializing write 0xF7 in I2C and Delay for 200 ms then write 0 for and delay 100 ms then do your other Initialization
 Sorry for bad English

From what I can see, it seems, in this line:
    LiquidCrystal_I2C lcd(0x27,20,4);

wrong parameters have been passed to the constructor. The last two arguments are supposed to indicate the number of columns and rows on the screen. Your screen has 16 columns and 2 rows, whereas you passed 20 columns and 4 rows to the constructor. This could be the problem.

source: Stack Exchange

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

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

sort: votes


text:
Problems returning char array from function, value gets messed up
I use the Base64 library for Arduino (but I don't think the problem is related to the library) and have the following function definition:
char* decodeImage(char inputString[], unsigned int inputStringLength) {
  int decodedLength = Base64.decodedLength(inputString, inputStringLength);
  char decodedString[decodedLength];
  Base64.decode(decodedString, inputString, inputStringLength);
  Serial.printf("%s",decodedString); // prints "Base64DecodeExample"
  return decodedString;
}

Later on, I use the following snippet to access the function:
  char inputString[] = "QmFzZTY0RGVjb2RlRXhhbXBsZQA=";
  char* output = decodeImage(inputString, sizeof(inputString));
  Serial.printf("%s",output); // prints garbage

The problem is, that the result of the decoding INSIDE the function seems to be correct, but when I return the value to the calling code, the value get garbled somehow.
I suppose this has something to do with pointer magic or "decaying" of references. Has someone a suggestion?

Your variable decodedString[] is created inside the function, used inside the function - and destroyed inside the function before it returns.
See how your function decodeImage() returns a char *? That's a pointer to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.
This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
You can make decodedString a permanent part of the function by making it static:
static char decodedString[64];

Note that the above two solutions have the same two problems:
  a. There is only one array. That means that if the same function is called again, it will overwrite the results from last time - use it before you lose it!
  b. You can't calculate the length and then use it - it has to be created at the maximum possible size.

You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function malloc and pass in the number of bytes that you want. It returns a pointer to that lump of memory:
char *decodedString = (char *)malloc(decodedLength);

Note that malloc doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the (char *) before the call to malloc does.
But if you use malloc, at some stage you must give the memory back with a call to free:
free(returnedString);

The function that did the malloc doesn't have to be the function that frees it - any function can, as long as some function does! Otherwise you'll run out of heap.
Another thing that you must NOT do is call free on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.
EDIT
There's a C++ version of malloc / free called new / delete. You use them similarly:
char *decodedString = new char[decodedLength];
...
// And later...
delete [] returnedString;

It looks and behaves similarly to malloc and free, without the ugly (char *) type-cast. Note that since an array was allocated with the new, you need to call the array version of delete by adding the [] as shown.

+1 for option 3. It avoids the bugs of global and disorderly access in option 1; the risks of over-writing of option 2; and the memory fragmentation of option 4. If the caller needs a larger return value than a single value, it provides the memory space for it. Of course if the caller isn't the end-user of the return, but has to return to its caller, the same conditions apply: caller's caller provides the memory, and so on up to the final consumer. Then it up to that consumer function('s author) how to allocate the memory buffer, but that is the one and only place that choice should be made.

... Coming to embedded systems from other environments, one will have seen all manner of "solutions" to doing this, including returning a local buffer and having gotten away with it (before the system ships!). An embedded system is expected to be able to run 24/7. "Fatal error: out of memory!" is not a option. Neither is stopping or any of the host of failures due to corrupted data. It has to "just work", and option 3 is the least likely to break.

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


text:
Running sensor input for given time, stopping, then running seperate scheduled relay output
I've set up an Arduino Uno to run a pretty basic garden watering schedule, with the delay function.
I've now built a solar thermal water heater with a pump and tried running it separately through a 555 timer using a thermistor (33k Ohm approx). I couldn't get this running as the change in resistance with a water temperature rise to 30 deg or so wasn't enough to trip and untrip the 555 timer (thermistor at about 20 k at 20 deg, maybe 50k at 30 deg). (Any pointers to circuits that achieve this would be appreciated by the way.)
I've decided to try to run the solar thermal motor with my arduino set up as I have 2 relays free in a relay shield. My question is how I can run the sensor to start the solar thermal pump, then stop operating the solar thermal system and return to the garden watering code, then restart the sensor input, and so on. The issue is that my power supply is only 1 Amp, and running both systems at once might overheat it.
Hope this makes sense,
Brian

Is the watering system running off the same relay board?

If you are just running the relays off the 1 Amp supply, and there aren't more than 6 relays they shouldn't draw more than an amp.(I will edit this statement if need be)
What you can do in the way of coding you can is to do a classic spinoff of using the millis() function.
//monitors temperature and schedules its operations
//RSM
#define TimeBetweenHydration 10000  //10 seconds
#define TimeBetweenThermal 1000  //1 second
#define Temperature_Thresh  25   //25°C

float temperature = 0.00;

unsigned long lastTempReadTime = 0;  //keep track of the time temperature was checked
//boolean MotorOn = false;  //state monitoring

unsigned long lastWaterTime = 0; //last time the system did something with the watering thing
//boolean Watering = false; //state monitoring

// other variables related to specifics
//…
//

void setup(){

//setup of analog inputs
//setup of digital pins

}

void loop(){

 unsigned long presentTime = millis();

if((presentTime - lastTempReadTime) > TimeBetweenThermal){
lastTempReadTime = presentTime;
 int inADC = analogRead(0);

  //do whatever conversion is needed to get a value of the temperature
temperature = inADC*3.14;

if(temperature > Temperature_Thresh){

//   if(!MotorOn){
     digtalWrite(RLY, HIGH); //turn on pump
//     MotorOn = true;
//  }
 }
  else{
  digitalWrite(RLY, LOW); //turn off pump
  }
}

   if((presentTime - lastWaterTime) > TimeBetweenHydration){
   lastWaterTime = presentTime;

//put your watering code stuff here

  }
}

If you want to make the pump run without a microcontroller you could use a comparator with the thermistor and use its output to switch a transistor. I do not have the 555 timer art skills.

T1 is you thermistor. You should use the values listed for R1 - R3. The transistor, coil and flyback diode are there to show how you should connect it up, the coil could be a motor or a relay to control the motor. The comparator changes around the 30-40Kohm mark.

Hi RMS, I really appreciate your answer, thanks.

In your schematic one leg of the relay coil (the one connected to the anode of the diode) connects to the transistor. I think the other leg of the relay coil (the one connected to the cathode of the diode) is missing a connection to +VCC (5v).

@linhartr22     yes it is missing the connection to 5V, 12V. The OP wasn't specific about there way the relays were hooked up and I didn't have a way to mark that with what I was using.

RMS, you are some man. I tracked down not an LM393, but an LM2904 and it took me a while, but it's working like a dream. Response time is great, and what a classy solution.

@BrianOCallaghan glad the circuit helped you, I think at a point certain things can be removed from the control of the  microcontroller and code ;). If you feel this solved the query, could you mark it as accepted to stop the system from bumping it and to help others looking for a solution.

I really appreciate your answer, thanks. I knew I'd have to let go of the delay function at some stage, and this is the moment I think ;)
As for the PS, I'm actually also powering two solenoid valves and the arduino through the same PS, so just being on the safe side.
I wasn't too happy with a transistor circuit I made previously, but I'll give yours a go for sure. I actually came up with a workaround, which is probably pretty lame. I rigged up a second 555 timer with a large resistor to switch on and off the supply to the first 555 with thermistor every minute or so (a la flashing LED). So the thermistor now goes to temp, switches on the load, but then won't switch it off; the second 555 then resets the first 555, load switches off and either immediately switches on again if at temp, or stays off. Pretty ugly, right!

The rig with the 555 timer sounds pretty good actually, you have made something that the code I did work in hardware.


text:
Arduino based temperature sensing circuit
I've currently got a setup where I am using a 2 thermocouple setup using MAX31850 and the circuit looks exactly as mentioned here using the external power option. (https://learn.adafruit.com/adafruit-1-wire-thermocouple-amplifier-max31850k/wiring-and-test)
I take the data that is returned from this over serial and pass it over to a simple inverter circuit, which inverts the signal and fluctuates the voltage of a small CREE LED.
The problem that I am encountering is that the data being received from the thermocouples is incorrect when the LED is attached to the setup. And it becomes correct as soon as the LED is detached.

I have tried running my thermocouple set up over an external 5V
supply and using common ground with the Arduino, but it still does
not help.
I have tried using decoupling capacitors on the power rails
to remove any noise due to the LED, but again to no help. What else
can I try to ensure that I can read the data and modulate the LED
simultaneously?

The question doesn't include details that would allow someone to replicate the problem and find out its cause.  "A simple inverter circuit" is vague.  Complete electrical schematics and some photos indicating layouts would improve the question.   ¶ You might try using optical isolators to transmit control signals, and run the LED with a separate battery.


text:
Arduino/C++ byte manipulation
Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.
Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.
eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.
01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1
What would be the most efficient way to accomplish this?

Could you explain a bit more? Is it always the same bits that are moved to the same new location? What values do the underscores (_) get?

Yes, the same bits are moved to the same new locations and the underscores are filled with bits which are calculated from the rest of the bits present in the received byte. (After performing a few simple operations on them)

Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:
int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 0x08) retval |= 0x800;
   return retval;
}

On most microprocessors, this will compile into just a few instructions per statement.
This is also arguably more maintainable than a complex series of shift and mask operations.

Assuming the incoming bytes are guaranteed to come in even numbers, and
your output is in little-endian order, you could do something like this:
void process_and_send_bytes(uint8_t data_in)
{
    uint16_t some_12_bit_function(uint8_t);  // processing function
    void send_byte(uint8_t);                 // sending function
    static uint8_t data_on_old = 0;
    static bool has_data_on_old = false;
    uint16_t processed_data = some_12_bit_function(data_in);
    if (has_data_on_old) {
        send_byte(processed_data << 4 | data_on_old);  // two pieces
        send_byte(processed_data >> 4);      // high 8 bits
        has_data_on_old = false;
    }
    else {
        send_byte(processed_data);           // send low 8 bits
        data_on_old = processed_data >> 8;   // save higher 4 bits
        has_data_on_old = true;
    }
}

Basically, when you get the first byte, this function outputs one byte
and keeps 4 bits on hold. When you get the next byte, this outputs the
4 bits that where on hold, together with the new 12 bits, as two
8-bit packets.

It looks like we each picked a different part of the question to answer! :-)

I haven't tested this in any way whatsoever, but you could use a 32-bit integer as a buffer to store the bytes as you process them.  Then, any multiples of 8 bytes that end up in the buffer can be passed on to wherever they are needed.
The first byte that comes in you process and push all 12 bits into the 32-bit integer - increment a counter by 12.  You now have 12 bits in the buffer variable.
Then while the number of bits in the buffer is at least 8 bits you grab the upper-most 8 bits and pass them on to wherever they are going.  Decrement the counter by 8 for each iteration.  You have now sent 1 byte and you have 4 bits left in the buffer.
The next byte that comes in you push the new 12 bits into the buffer.  The counter, increased by 12, is now 16.
16 is greater than or equal to 8, so send out the upper 8 bits of the 16 and decrement the counter by 8.
8 is greater than or equal to 8, so send out the upper 8 bits of the 8 and decrement the counter by 8.
Counter is now 0, so nothing else to send.  Back to the beginning again.
Something like:
void processByte(uint8_t in) {
    static uint32_t buffer = 0;
    static uint8_t validBits = 0;
    buffer <<= 12; // Make room for 12 new bits.
    buffer |= (first processed bit << 11);
    buffer |= (second processed bit << 10);
    buffer |= ((in & 0x80) << 2);
    buffer |= (third processed bit << 7);
    buffer |= ((in & 0x70) << 1);
    buffer |= (fourth processed bit << 4);
    buffer |= (in & 0x0F);
    validBits += 12;

    while (validBits >= 8)
        validBits -= 8;
        executeByte((buffer >> validBits) & 0xFF);
    }
}


text:
Serial Error Correction
I currently have a setup where I take serial output from Arduino 1 and push it through a transmitter to the receiver of Arduino 2 where it is fed back into the serial input and further processed. I want to ensure that there is as little error as possible and recover the data wherever possible.
I have come across the syndrome decoding technique which seems to be the ideal one for me, but I am confused as to how I would go about implementing it.
I know that the Arduino Serial transfers data byte by byte, each being 8 bits, but do not know how this data is sent over the serial connection (i.e. how the start & stop bits & parity is implemented).
I would assume that a solution to this could either involve modifying the data in the buffer or reading it from the buffer and then operating upon it. I could also use adjacent bytes of data for error correction, but this seems wasteful.
How should I proceed with this?

Which "syndrome decoding technique" are you considering?  It will probably affect the approach.

Welcome to the wide world of Communications.  You are asking about "Error Detection and Correction".  This is different from "framing", which allows you to determine when a message starts and ends.
With "error detection", you know there was an error, but you can't necessarily recover from it.  With "correction", you know there was an error and you can determine what was originally sent.
This always requires extra bytes.  There are many schemes, but the Fletcher checksum for Error Detection is easy to implement, fast, and only requires 2 extra bytes in the message (4 if hex digits).
The generic approach is to use a finite-state machine.  In complicated message protocols, there would be nested state machines: the inner-most would probably determine framing, the next one out might looks at addressing, etc.  Any or all of those layers could use Error Detection and/or Correction.
For your simple "protocol", a single state machine is probably sufficient.  The states might be IDLE, RX_PAYLOAD and RX_CS.  As characters are received, they are processed according to the current state and occasionally change the state variable.
while (Serial.available()) {
  uint8_t c = Serial.read();
  switch (state) {
    case IDLE:
      if (c == MSG_START)
        state = RX_PAYLOAD;
      break;
    case RX_PAYLOAD:
      if (c == MSG_END) {
        state = RX_CS;
        cs = 0;
        csCount = 0;
      } else if (length < MAX_LENGTH-1) {
        msg[ length++ ] = c;
      }
      break;
    case RX_CS:
      //  Add in the next hex CS digit
      cs = cs * 16 + fromHex(c);
      if (++csCount == 2) {
        // both digits received, see if the CS matches
        if (cs == csOfMsg( msg, length )) {
          // Handle the message
          msg[ length ] = '\0';
          Serial.println( msg );
        } else {
          Serial.println( F("Bad message!") );
        }
        state = IDLE;
      }
      break;
  } // end switch
} // end while

There are entire books written on protocols and their design.  This is just a made-up example to give you an idea of how it should be structured: a finite state machine, driven by received character "events".
Sometimes you can compute the checksum as the characters are received, like Fletcher.  Here, it waits until the entire message plus 2 CS bytes are received.

In my case i used a buffer and a delimiter. Specificaly: The reading is placed on the byte array untill the delimiter is reached.
For example
From the arduino IDE serial monitor im sending this: CAT;
Each letter will be placed inside the byte array and this will stop when the ; sign is entered. This migh be usefull because you can send the bytes whenever you can and they will remain in the array.
void loop(){
if(Serial.available() > 0) {

 char rec = Serial.read();

 if(rec == '.'){
    Serial.print("Here: ");
    for(int i = 0; i < sizeof(attitude); i++){
       Serial.print(attitude[i]); //print
       attitude[i] = (char)0;
    }
    attitudePointer = 0;
    Serial.println();

 }else{
   if(attitudePointer <= sizeof(attitude)){
      attitude[attitudePointer] = rec;
      attitudePointer++;
    }
  }

 }
}

That code doesn't match your description!  That code waits for a period (full stop), not a semicolon.  And it's a little misleading to use attitudePointer, when it is actually an index, not a pointer.


text:
What info should I look for when choosing a solid state relay for arduino?
I want to control a phone using an arduino board by connecting each pin of the arduino to a button on the phone using relays to simulate a button being pressed or release by switching a relay (on/off). I am using relays because from what I have seen (Use Arduino to Switch Power On and Off! ) relays are controlled swiches and I am using SSR because I want to use the less space possible.
I'm trying to buy a relay at mouser.com but I don't know what are the values I should look for, for those parameters (Control Voltage Range, Load Voltage Rating, Load Current Rating, Input Current).

You need to look at everything.

@IgnacioVazquez-Abrams yeah but I don't know what are the values I should seek

Do you know how a relay works?

All I know is that a relay has often 4 "inputs" 2 that I can use to connect a controller (the arduino) and 2 I can use to connect the controlled component (a button on the phone). I also know that mechanical relay (on the video) use an electromagnet on the control end to close the circuit.

Why use a relay for this? You can probably do this with some simple transistors. Or if you like the isolation, opto-couplers. What kind of phone are you talking about?

What do your phone buttons need?

An SSR is not a good choice for your application.  The common use of an SSR is for switching on and off an AC load.  If the data sheet mentions SCR or Triac, then it is meant for only switching AC and will not function for controlling DC.  So keep this in mind when looking for components: if it says "24-220 VAC" on the data sheet that does not mean it will work for DC.
A second common use of SSR and microcontrollers is the opto-coupled input type.  That input method provides a safe scheme for a low voltage low current control signal to switch a large load.
For a button on a phone, you are switching a near zero current DC load.  You should be able to control that with a transistor, but that would require some reverse engineering of how the phone keypads where being scanned.  You would need to trace out what the voltage was, how much voltage drop could be accommodated.
A certain easy method is to use a small reed relay.  Parts are available that have a coil that only draws ~10 mA so can be driven directly from an output pin.  The relays are packaged in a DIP so easy to prototype on a breadboard.  Many list the coil resistance and voltage for specs, for example a 5V and 500 ohm resistance coil would draw 10 mA.  You will find many for 1 - 2 $US.
When working with a relay, you need to take care of the back EMF (aka flyback voltage) that occurs when you turn off.  That is handled with a single diode which you will see in every schematic for driving a relay.  For a beginner, an alternate/sure success route is to use a driver chip such as a ULN2003 that will drive inductive loads such as small relays.

I would tread carefully. A solid-state relay may or may not be suitable for the relatively low-level signals present across the phone buttons. Check the datasheet, buy just one, and try it out.
But do you need to control a physical phone? An Arduino can connect to a standard modem which has inbuilt commands to dial numbers and generally supervise a phone line.

If you're only controlling a button, the load current and load voltage are pretty much irrelevant since I'd be surprised if you even used 5% of it's rating in either category. I can't tell you how much you'll need here since I don't know the voltage that the relay will be operated on and the resistance of the path for the load.
What you do need to look at is the voltage and current of the input/control/logic signal. It should allow a 5V control voltage and the current draw for that logic signal should be no more than 40mA, although it's ideal to stick to a lower number (say, 30mA).
However, manually picking out a relay manually isn't ideal for a beginner since it requires a bit of extra components to properly run. A relay module (Amazon) allows you just hook up your wires to the jumpers and terminals of the relay module without any extra soldering (as far as I know they aren't breadboard compatible, thus requiring a custom PCB or having it "flop") or parts.


text:
Arduino + ultrasonic rangefinder behaving unexpectedly
I'm using an HC-SR04 ultrasonic rangefinder to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given here):
#define trigPin 10
#define echoPin 12

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(9, OUTPUT);

}

void loop() {

  float duration, distance;
  digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin
  delayMicroseconds(30);

  digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
  delayMicroseconds(30);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); //Defines the duration variable

  digitalWrite(9, HIGH); //square wave oscillator
  delay(0.1+duration*0.01);
  digitalWrite(9, LOW);
  delay(0.1+duration*0.01);
}

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

@DaveTweed: I reckon this shouldn't have been migrated. The problem is probably in the hardware specification. See my answer.

I do not really understand the behaviour of your program, but I would
like to point out a couple of points that may be problematic:

Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as
the program you based yours on, yet you have a 30 µs delay. If
this extra delay makes you miss the rising edge on the echo pin, then
pulseIn() will believe it is seen the previous pulse, and it will
wait for the next raising edge before starting its measurement. Since
that next rising edge will never happen, pulseIn() will eventually
time out after one second. This is probably the silence you are
hearing.
Your sound frequency may not be what you expect, because the time
needed to run through the loop is not only the two calls to
delay(), but also the time taken by pulseIn() and the various
delayMicroseconds(). You should have more consistent timings if you
use the tone() function instead of trying to bit-bang the sound.

Your comments don't match your timing delay values and the datasheet specifies a 10 µs pulse. You're giving it 30 µs but you might get away with it.
I'd look at how often you're triggering the device.

Figure 1. Don't trigger the device more frequently than 40 times per second.


text:
Serial communication between arduino and raspberry pi works once, then stops working
I'm using a Arduino Uno Rev 3 connected over usb to a Raspberry Pi Modell B+ running Rasbian.
Here ist the arduino code:
int input = 0;
String command = ""; // beinhaltet den aktuellen befehl
int Action = 1;

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

void loop() {
  if (Serial.available() > 0)
  {
        input = Serial.read();
    char currentChar = input;

    if(currentChar  == '!') // frage nach trennzeichen
    {
      Serial.println(command);
      //Serial.write(Action);
      Action = command.toInt();

      command = ""; // befehl wieder leeren
    }else
    {
      command = command + currentChar ; // falls noch kein trennzeichen vorhanden, erweitere kommando
    }
    }
}

Here is the Raspberry Pi code (in python)
import serial
from time import sleep as sleep
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0]
while True:
        ser.write(b'2!')
        a =  ser.read(1)
        print a
sleep(2)

It always works if once after the code was uploaded to the arduino, but if I stop the script on the pi and restart it it stops working. What is the problem here?

Does the PI close the serial port as it exits?  If it doesn't can it open it again?

It works on my PC running Ubuntu, although it prints tons of CR and LF. You may have noticed that you are overflowing the Arduino's input buffer.

@EdgarBonet how do I prevent the input buffer from overflowing?

Speak slowly, e.g. by moving the sleep(2) inside the loop. You may also want to read the whole answer (3 bytes) in each iteration.

You do know that the Uno resets, when you create a new serial connection to it, right?

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

"It always works if once after the code was uploaded to the arduino...."
Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.
Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!


text:
Connecting (SD or HD) TV screen to Arduino
I had a thought about making myself an arcade cabinet. I found a nice cheap and sturdy 8 directional arcade joystick online, and now I'm thinking about the possible ways of displaying graphics.
I would like to know how can I send graphical data to a large screen using Arduino. When I was researching this I saw "TV Text" library that allows sending PAL and SECAM signals, but that's not the "modern" way. Is there a way of using DisplayPort or HDMI to simply use a cheap used PC monitor? Maybe there are other protocols that I can use? I'm looking for a "cheap" way to create a display that's physically as large as screen of arcades from "the good old days".

If you can find one (they're discontinued now, so you will only get a used one), you want one of the original Gameduino shields. Then you can use VGA.

Better would be to ditch the Arduino and use a Raspberry Pi with the RetroPi operating system image.

@Majenko I understand there are many "out of box" solutions that handle games, but I just want this project to be an excuse to gain the know-how to create high quality display with my hardware in the future. I'm looking for some way that doesn't require using retro hardware, and can be used in my future proijects.

https://www.gammon.com.au/forum/?id=11608 -> https://www.youtube.com/watch?v=dtfNhh6GZ-s

Also if you don't want to use ready-to-go solutions, ditch the Arduino. Especially with AVR based Arduinos you will never get something that can be in any way called "high quality" and when adding functionalities you will run very fast into pure physical limitations. Doing this with an AVR Arduino can be called masochistic.

I agree with the other posters that the Arduino just isn't up to the job. It doesn't have any native display hardware, and an AVR-based Arduino isn't up to the job of doing it through software. The Arduino is good at I/O. Use a PI if you want to drive a display.

I'm just going to post things that I found thanks to comment by Juraj.

"TV Text" library - PAL, SECAM, NTSC
"VGAX" library - VGA

And with large dedication to everyone who wrote that "it's impossible" I give you a blog post of someone who actually did create he's own NTSC console and a game from scratch (called "The Box") using ATmega328P with external 16Mhz crystal. And he did it in 2013.
http://petenpaja.blogspot.com/2013/11/toorums-quest-ii-retro-video-game.html
Original sources were deleted, but I think they can be found when looking for Toorum Quest 2
I think I'll try analyzing the VGAX. It looks promising.
EDIT:
There actually is HDMI shield for Arduino!
https://github.com/techtoys/HDMI-Shield/tree/master/Ra8876_Lite
And a nice and very easy VGA tutorial here:
http://www.pyroelectro.com/tutorials/arduino_basic_vga/

I tested TVout library once. It uses composite video signal. The demo has a rotating 3D wireframe cube. https://www.youtube.com/watch?v=ZT46khR2A3c

I think most of us stumbled across your phrase "high quality". The quality, that you can get from it is very limited. You won't get video quality that can hold up to the standards we are accustomed to from HDMI and Displayport. If this is sufficient, then of course it is possible.

@chrisl There actually is a solution that gives you "high quality" It just costs 50USD https://www.youtube.com/watch?v=MUeIY_gLn3c

That looks quite interesting. Good to know, that you can buy such a thing. Though it is worth mentioning that it doesn't seem to work with an Uno. My guess is, that AVR based boards will not work with it.

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


text:
Can adjustable constant current/voltage source be made with Arduino?
I would like to create a 18650 battery automatic management system that can handle and restore used up cells using solar panels for power. To do that I need to create adjustable constant current source that will limit the current/voltage going into the cell/cells to a small enough value.
Since there are more features I would like to implement (like checking cell capacity) I would love to use Arduino with least amount of components as possible to keep the cost down.
My first question is: Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?
The pseudocode for logic I'm proposing is simpe:

Use ADC to check voltage on the capacitor (or a very small value power resistor when working as current source)
Calculate required voltage adjustment
Use AnalogWrite to set new PWM value into internal PWM controller.

Second question: PWM causes a lot of "switching" in the MOSFET. When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss? Since the batteries have some internal resistance voltage variation of +-20% should be acceptable.

When you have to ask, don't do it. The risk of damaging the battery is too high. There are dedicated chips to charge batteries. I suggest to buy a charger from a well known brand.

The dedicated chips work great with new and shiny 18650. The used up ones have special needs. At this moment I'm restoring them by hand one by one. For example first hour of charging cannot exceed 50mA if voltage of 18650 was initially less than 1,5V. I was able to get 1500mAh (out of nominal 2500mAh) from cell discharged to 0,5V taken out of old laptop. I would prefer to delegate this task to Arduino because it takes a lot of time, and checking the cell temperature every 10 minutes is tedious.

There are dedicated charge ICs that will trickle charge if the voltage is too low. Check the datasheet. I’d use a dedicated chip for charging. And use an Arduino to measure capacity. Or buy a charger-doctor from China that measures the mAh for you.

I already have all the stuff you can buy from china, but I had to modify most of it because it tends to overcurrent (it starte with 100mA and not 50mA) and overvoltage (charges up to 4.26V) batteries. I'm trying to design a universal (and cheap) solar powered "used battery management system" that might end up being a KIT at some point. I would like to prototype it with Arduino before I rewrite everything for native execution in ATtiny/ATmega or something similar. I tested that Arduino Bootloader makes ATmegas run much slower in some cases.

you can slow down either side's voltage variations with a capacitor. you can pick one large enough to guarantee you plenty of time to read the ADC.  2. you can safely assume MOSFETs switch instantly for your practical application, which at 5v is pretty close to true for logic-level FETs and sub-1amp loads. secondly, the internal resistance is so small anyway (milliohms) that it takes several amps to even slightly warm them.

You are basically describing (if you add an inductor and a diode into the mix) a simple switching regulator.  That is, at its simplist, a PWM signal, some smoothing (inductor, diode, capacitor), and feedback.
Use the Arduino's PWM to switch a P-channel MOSFET in the voltage supply. That switched supply is then fed through an inductor, and then smoothed with a capacitor:

simulate this circuit – Schematic created using CircuitLab
M1 does the switching of the power to charge the rest of the circuit.  L1 + C1 smooths the PWM out giving a constant smooth (ish) voltage. D1 completes the circuit between L1 and C1 in one direction only keeping the charge in the right part of the circuit.
R1 keeps the MOSFET turned off when not being driven.
R2 is a very small "shunt" resistor (maybe 0.1Ω for example).
The size of C1 and L1 are determined by the switching frequency of your PWM and the current demands of the circuit.  The higher your switching frequency the smaller your inductor can be, The higher your current demands the larger C1 needs to be.
Reading A1 gives the output voltage of the circuit, so you can adjust the PWM (using PID would be good) to get a specific voltage.
Reading A0 and A1 and subtracting one from another gives you the voltage drop across R2. From that, you can calculate the current through R2 using Ohm's Law. You can then use that to adjust the PWM to give you a specific current.
Of course, you can't do both at once. You either have a constant current (during the first charging phase to bring the cell voltage up to 4.2V), and then switch to constant voltage until the current drops to around 0.3C.  For dead cells, an initial constant current phase of (IIRC) 0.1C can recover the cell.
Some important notes about lithium cells:

They explode (just ask Samsung), so take care. It can be good to do your experimenting with the cell contained within a fireproof container.
Lithium Ion and Lithium Polymer cells don't like being over-discharged, but as long as they haven't been reverse charged they can generally be recovered.
Cells that are used in a series pack and haven't been charged with a proper balancing charger may well have been reverse charged if the pack has "died".

The reverse charge thing is what actually kills a Lithium cell.  Basically, no two cells will have exactly the same capacity. If you have, say, three cells in series and you discharge the whole pack to below the recommended minimum, once cell will have less charge than the others. If that cell hits zero the current from the other cells will start flowing backwards through it, and that backward current causes copper crystals to deposit on the electrolyte layer between the electrodes. Those pierce the electrolyte layer and short the two electrodes together, and at that point the cell is dead. No amount of recovery charging will get it back, it's physically damaged.
So in summary:

A single cell that has been over-discharged by itself will generally be recoverable.
A series pack of cells that has been over-discharged may well have physically damaged one of the cells in the pack through reverse charge flow.

Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

Sure. You should pre-condition your power so it is always within a tolerable limit (i.e., feed your solar panel power through a suitable 5V buck regulator to give a clean 5V supply). There will always be some latency in the circuit due to how long the inductor "resists" changes in the voltage. A typical Arduino takes ~100µs to sample an ADC. In this kind of environment, that time is negligible since it's generally much faster than a single period of PWM. You can't respond faster than one period of PWM anyway.

When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss?

That's what PWM does. It's ON or OFF. On at the start of a cycle, then off part way through.  Yes, there is a brief period twice per cycle while it does the switching, but that will be minimal compared to the on and off periods. The losses from that switching will be negligible compared to, say, running a MOSFET as an adjustable resistance controlled from an op-amp with feedback from a current shunt (i.e., a linear regulator).

Thanks for the general answer, but you didn't address my questions. The solar panel provides a "random" voltage anywhere from 6V to 48V and my question is if the Arduino at least has the chance respond fast enough to dynamic changes. ADC measurement takes time, logic takes time, changes to PWM take time and in that time voltage on regulator output can escalate making a lovely red lithium colored fire. Physically broken cells can be easily detected. They don't decrease current in last phase of charging (and heat up) or they have high self discharge rate. I use old laptop batteries for cells.

@FilipFranik Since you don't specify any specific Arduino, yes, there are "Arduinos" that are plenty fast enough. Probably even a simple Uno would be fast enough. Especially if you first pass your solar cell power though a normal switching regulator to give a steady 5V - that way there won't be any surprises. Also the indictor works two ways: Not only does it try to keep the voltage up when the fet switches off, it also tries to keep it down when the fet switches on. You don't get instant rises on the output because of spikes on the input.


text:
Bidirectional communication between Arduino and Raspberry Pi over USB possible?
Is it possible to have bidirectional communication betweeen an Arduino Uno Rev 3 and a Raspberry Pi Modell B+ running Rasbian? They're connected ofer USB, and it would be good if I could use Python on the Pi.

Other than with the normal serial object?

@IgnacioVazquez-Abrams can you explain what you mean? Sorry I'm pretty new to this

Yes.  The Arduino Uno implements a serial protocol inside the USB signal using hardware.  This is how it is built.  The Linux side is a bit more complex as there are many USB protocols.  Here is a howto which talks about the Linux side of the Arduino / Linux connection.
To be clear, Rasbian is a derivative of Linux.

Yes, it is possible to have a USB serial communication between a raspberry pi and an Arduino. And it is  much more easier when using Python on the raspberry pi.
Python has a serial library within it's standard library which you can import on the raspberry pi and then use it to send or receive data to/from the Arduino or the raspberry pi.(Just connected via USB cable).
Here is the link for a very similar requirement on YouTube.


text:
Doorbell for someone with hearing issues
I have an Arduino Uno with the basic kit, not very good at coding it however.
How could I make a doorbell that lights up an LED instead of making a noise?
I'm trying to make a doorbell for someone with hearing issues.
A simple LED lighting up would be more than enough. Would I need a wifi shield if it's not close enough to be hard wired?
Thanks

I know you are keen on using your Arduino.  But simpler solutions abound.  For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.
However, I can see a situation that an Arduino can fit very nicely into:
Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino.  4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).
There are 2 tricky bits that may need explaining.  The first is how to sense the door bell.  If mechanical you could use a micro switch:

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid.  The other tricky bit is controlling a room light.  I would suggest using a COTS remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.

If you must do wireless, you can get by with a 433MHz rx+tx module. Be sure to align both antennas either vertically or horizontally. These modules kind of need two MCUs though, but clones are cheap. Personally I would add a small switch underneath the doorbell button, but separate from its circuitry. Debounce it. On the receiving end you need a good set of LEDs - iphone has a very annoying but attention-grabbing light pulse for people hard of hearing. You can see it on youtube. I would copy that pulse timing and intensity as closely as possible, thus infringing on Apple's no doubt copyrighted+patented 'technology'. Be a pirate, arrr!


text:
Cannot find COM port for Arduino after replacing Atmega328p
I had mistakenly burnt my ATmega328p that was there on the Arduino UNO R3 board. So I bought a new ATmega328p-pu with Arduino UNO bootloader installed and a sample blinking LED program pre-flashed.
However when I replaced it and plugged in to the PC using the provided Arduino programmer cable, I could not find the COM port in the device manager in Windows and neither in the Arduino IDE.
I should also mention that when I put the new Atmega328p-pu into the Arduino UNO board, the LED at 13 or L did start blinking. So I am inclined to think that both the bootloader and the sample program are there. But I cannot find the required COM port.
How do I fix this?

you should see the com port on the computer even without a chip. try rebooting.

Maybe the ATMega328P-PU isn't the only chip you blew up...?

@dandavis I could see the COM port in the device manager as a hidden device but it wasn't "active".

I agree with @Majenko.  Think of all the connections on the board, and the current path it would take to fry the CPU.  It must have gone through other components on the way.  Might be time to try another board to eliminate the possibility of it being a bad cable or a computer software problem.  .

Alright I might have fried the some other component on the board. I'll try something else. Thank you all for your replies.

My very first Arduino board had a bad UART on it. I can't believe how close I came to giving up before requesting a replacement board. I was just so sure I had messed something up.

Putting the ATmega into the socket backwards could potentially short out the board, and either prevent the USB chip from working or cause the PC to shutdown that USB port.

Then check wheather the problem is with your computer or the arduino.if it is with your arduino, consider replacing it. Check the arduino internal circuit for any burns

Generally the IDE will detect one it can use, so you shouldn't need to use the Device Manager.
When you select the board type, so far, so good.
Then when you ask it to pick the port, it will present a list of ports that it has discovered that are registered in the Device Manager.
One thing you will notice is that if you have a Genuine Uno, for instance, it will list that next to the port name.
But if you are using a board (of any type) that have the CH340-type port it will show just the COM9 or whatever it finds.
If it doesn't find any ports (My laptop always detects the COM1 port on the back that I never use so in my case if that is all it finds then it is not finding any USB ports)  then jump ahead to the arrow below.
So by trying each one you will find a port that works with your board.  Or not.
I am sure you have already seen the errors it throws when you use a port that won't work for you.
----->  If you have tried all the ports listed and none works, then you are left with only a couple of possibilities:  Either the cable is bad, or the board is not responding.
Ultimately, it doesn't matter what it says in Device Manager if the IDE won't use it.
So if you can find another board and see if the cable works that would eliminate the cable as being a problem.
But if it simply will not respond then look above in the comments at what @Majenko said.
Good luck.

Just a heads-up, this answer has been flagged as low quality. You might want to do something about it and expand upon your answer, before it gets deleted. It is rather terse, as it stands, tbh.

Thank you, @Greenonline.  I was tired and at the end of my work day when I posted that.  I agree that if I was reviewing it I would at the very least have said that it looks more like a comment.  I really appreciate the heads-up.  I hope this is better.  I know for sure that it works like this because I have had a bad cable that made me doubt brand-new Nanos.  I put three of them in the ? box before I decided to change cables and Amazing Grace they all worked.  TNX again.  Have a great day!

I met her once. She wasn't that amazing...

Heh, heh!     ;-)  That's pretty funny.


text:
Comparison of Board Shape between Arduino MEGA and Arduino DUE
I'm using KiCAD to design boards, and while it has a lot of Arduino templates, it doesn't have one for the Arduino Due. Now, I've did some searching, and it looks like the Arduino MEGA is very similar to the Arduino DUE, not the specifications, but the number of I/O pins and the overall shape of the board. I couldn't find a straight answer, so I decided to ask here: Can the template of the Arduino MEGA be used as a template for the Arduino DUE when designing custom 'shields' and such based on the number of I/O pins and overall layout?

The Due has the same footprint as the Mega 2560.

source


text:
Pins are not switching
I am trying to make pins 13, 12, 10 and 9 to switch between high and low. That is, when pin 13 is high, pin 12 should be low, then pin 10 should be high and pin 9 should be low.
Code:
 unsigned char driver[4] ={13, 12, 10, 9};
 String mystring = "";
 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   for(int i = 0; i < 4; i++){
     pinMode(driver[i], OUTPUT);
   }
 }

 void backward(){
   digitalWrite(driver[0], HIGH);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], HIGH);
   digitalWrite(driver[3], LOW);
 }

 void forward(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], HIGH);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], HIGH);
 }

 void STOP(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], LOW);
 }

 void loop() {
   // put your main code here, to run repeatedly:
   while(Serial.available()){
     delay(10);
     char mychar = Serial.read();
     if(mychar == '\0')
       break;
     mystring += mychar;
   }

   if(mystring == "F" || mystring == "f"){
     forward();
     mystring = "";
     Serial.println("moving forward!");
   }

   else if(mystring == "B" || mystring == "b"){
     backward();
     mystring = "";
     Serial.println("moving backward!");
   }

   else if(mystring == "S" || mystring == "s"){
     STOP();
     mystring = "";
     Serial.println("stopped!");
   }

   else
     mystring = "";
   }

When I test it, there is no switching, that is when moving backward, pin 13 is high throughout, pin 12 is low throughout, pin 10 is high throughout, and pin 9 is low throughout

Also posted at https://stackoverflow.com/q/44594985.


text:
Dimmer on Due: digitalWrite on one pin affects digital value of another
I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme:
My scheme has MOC3043 with zero-crossing detection.
I use two pins to control the dimmer: detectorPin to analyse input voltage wave and controlPin to drive optocoupler. The program is very simple thanks to zero-crossing MOC.
I attached an interrupt to the input detectorPin on CHANGE event. And controlPin is used as digital output. When I test detection with controlPin unplugged everything works fine. But when controlPin is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when controlPin value is set to HIGH with help of digitalWrite() func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.
I measured current on the controlPin, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.
I tested this with detectorPin = 51, and different controlPins: 52, 36, 31.
So, how do you think, what is the problem? Is my Arduino broken?

What happens if you remove the traic (T1)? Do you still get the error?

What is the mode of the control pin ? INPUT or INPUT_PULLUP? And the I/O circuits have common ground with your Due, right?

@Gerben, I don't know, I will check.

@JanHus, mode is INPUT, there is external 10k pullup. Yes, right, circuits are attached to one of GND pins on Arduino.

The problem with wrong input was caused by floating base of optocoupler:

100k pull-down will fix it.

There are a few issues with your circuit.
First, you need to add a diode to your 4N25 circuit. See EDIT below.     You should still put a diode across your 4N25 LED.  Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.  Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts.  Using devices beyond their "maximum specification" can produce unusual side effects.
Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC,  and be protected against overvoltage during the other half of the cycle.
Second,  rearrange your circuit for the Triac.  The data sheet for your MOC3043 triac driver shows a typical schematic.

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit.  This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.
Without seeing your code, I can't say much on that.  However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation.  You can reduce the resistor to achieve higher current to the MOC3043.
EDIT  :  I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.

Hi, thanks! First of all, this is not my scheme, I have different resistors and bridge, this is just example image from the internet. Second – all your notes are not concerned with problem in question. And I know that current is too low, I write this information to emphasize that there is no overcurrent through the pin.


text:
Does MFRC522 supports native SPI of Arduino Due?
Does MFRC522 library support native SPI interface of Arduino Due?
By native SPI I mean this one:

I came here with this question because the initializer asks for 2 pins: SS and Reset:
MFRC522(byte chipSelectPin, byte resetPowerDownPin);

SS pin can be any, but what about Reset?

There is no reason why it wouldn't support the Due's SPI. It just uses the default SPI.h library as the interface.
The resetPowerDownPin can be anything you like. It is not part of the SPI protocol but specific to that library. It is just controlled with digitalWrite() internally.
If you don't want to use the functionality you can set it to MFRC522::UNUSED_PIN and it will be disabled.

I tested it, it actually works.

You have a typo, should be MFRC522::UNUSED_PIN.

@kelin Indeed it should. Well spotted.


text:
Arduino Due: ADC gain adjustment problem
I want to increase gain of the ADC channel. To achieve this I'm using adc_set_channel_input_gain function from adc.h. Here is the entire sketch:
const byte aPin = A6;

void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);
  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}

void loop() {
  int analog = analogRead(aPin);
  Serial.println(analog);
  delay(500);
}

The problem is that output values are not depending on the gain value.

The function adc_set_channel_input_gain() is not compliant with the basic analog input library which use only analogReadResolution() and analogRead(). Please read more about adc_init(ADC... for the "sam3x".

@J.Piquard, thank you for help, where can I find documentation?

Take a look to that Guide: "Quickstart guide for SAM ADC driver".

Well, the solution was very simple. We just need to call adc_enable_anch() before changing gain or offset of the ADC. I improved my setup and the sketch works as expected now:
void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_enable_anch(ADC);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);

  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}


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

You can't have 4 of those on one bus. The maximum is 2.
The pin SA0 defines the least significant bit of the I2C address. From the datasheet:

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

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

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

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

Majenko, didn't you know ? The method in the link provided by @gre_gor has been tested and is working for a MPU-6050. It might work for a MMA8451 as well. All the sensors should be kept at 0x1D, en only one to 0x1C to control that one. Since the MMA8451 can not handle 5V signals, the signals to the SA0 pin must be lowered to 3.3V signals (to switch the I2C address). Another option is to use software I2C, perhaps even with a shared SCL pin and with seperate SDA pins for each sensor.

That's an interesting concept. As long as the chip can change is address realtime like that it could work. If it reads the pin at power on only then it won't. Give it a go, it may work. If not you'll need a second bus or multiplexer.

Power them on one at a time. They don't take much current to run so a GPIO pin would be more than sufficient.

A I2C device that is powered down pulls down the SCL and SDA, making the I2C no longer useable for others.


text:
Sensor for turning rail direction
I am trying to control an actuator carrying a carriage made from stepper motor. My problem is that after the carriage reach certain height, I want it to delay for several minutes and change direction to move the other way around.
Any suggestion on what sensor to use? I tried to use EndStop switch like the one in 3D printer but I haven't found any luck as it simply cuts the electronic connections once the carriage hits it.

Sounds like it depends on your mechanical setup, but how about a microswitch? Or a hall-effect sensor?

If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing.  From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

(Diagram by Majenko)

I usually use draw.io for my block diagrams. Gives much more professional looking results with less effort ;) Like this: http://majenko.co.uk/resources/Stuff.png

@Majenko - Shhh.. don't tell anyone but I'm at work and was limited to Word.  :)  I'll check it out, thanks.

It's a website. No need to be "limited" these days ;)

Thank you!! I just tried it last night with 'switch' and it works beautifully


text:
Taking pictures with a small Arduino
I'm trying to make a time lapse video of a crystal patch in a small space.  I need some way of taking a picture every hour or so within an area no greater than 35mm, the smaller the better.  Something like the Arduino-Leonardo-Beetle would be the ideal dimensions.  What sort of camera and Arduino board do people recommend?  Thanks!

While not entirely impossible, an Arduino is not suited to this, something already explained to you when you asked this on EESE: https://electronics.stackexchange.com/questions/312692/arduino-beetle-and-camera

I'm just looking for a second opinion.  You've told me on two different boards that it isn't entirely impossible, but both times you haven't offered any suggestions on how to go about it in the (admittedly small) realm of what is possible.  I don't intend to sound rude, but if you insist on following me from board to board to comment on how it isn't entirely impossible, would you kindly at least offer some advice on how to perform this operation instead of just saying it wouldn't be your top choice of doing it and downvoting me?

I didn't downvote your original posting, someone else did.  And I already mentioned buffered cameras but that even with that the lack of memory on an Arduino still makes things very challenging.  You are wasting your time and money to pursue this with an Arduino.

Many digital cameras, and even some motorized analog cameras, can be triggered by a wired remote. You can replace the remote by a relay, and have the Arduino drive the relay through some sort of transistor.

Sounds like the issue is space. Can you use a camera like this connected to a RPi? The ribbon cable allows you to place the RPi outside the container (I assume the crystals are in some type of enclosure). With the RPi, you would probably not even need any coding.

Yeah @Johnny, this ought to work!

Check out Arducam. I have used it and the library is maintained.


text:
What do the pins on this KS0107+KS0108 display do?
I got this display on ebay and I have no instructions on how to use it. I can guess what most of them do but I'd rather be sure I know what they all are instead of messing around trying to guess. The ebay page said the screen is a KS0107+KS0108 128x64 display.

Is there any documentation on what these pins do and which ones I need to connect to my arduino uno to get it working?

glcd-arduino (GLCDv3) is an unofficial Arduino library that supports Graphic LCDs (GLCD) that use the KS0108 (or equivalent) chip.

Ah I see there is a diagram there with the numbers 1-20. Is this some kind of standard arrangement for these kinds of LCDs?

In most cases, yes. Sometimes there are LCDs in which CS1, CS2 (CSEL1, CSEL2 ) have an inverted input.

This LCD corresponds to Pinout B according to the table.


text:
delay() runs super fast unless I remove a while loop that never runs
I'm working on a small game on arduino but I'm facing some really odd behavior. When I run this code all of my leds flash on and off in less than a second even though delay(10000); should stop them for 10 seconds. However if I remove the while(game_running) block they go back to flashing every 10 seconds even though that block of code never actually runs.
int yellow = 12;
int green = 10;
int red = 9;
int blue = 11;

int debug = 13;

int sequence[1000];
int level = 0;

int game_running = false;

void setup() {
  pinMode(yellow, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);

  pinMode(debug, OUTPUT);
}

void loop() {

  // Pre Game light flash
  digitalWrite(yellow, HIGH);
  digitalWrite(green, HIGH);
  digitalWrite(red, HIGH);
  digitalWrite(blue, HIGH);
  digitalWrite(debug,HIGH);
  delay(10000);
  digitalWrite(debug,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, LOW);
  digitalWrite(red, LOW);
  digitalWrite(blue, LOW);
  delay(10000);

  game_running = false;
  level = 0;

  while(game_running) {

    sequence[level] = random(4); // Select next color

    // Blink LEDs
    for (int i=0; i < level; i++) {

       if(sequence[i] == 0) {
         digitalWrite(yellow, HIGH);
         delay(1000);
         digitalWrite(yellow, LOW);
         delay(1000);
       } else if(sequence[i] == 1) {
         digitalWrite(green, HIGH);
         delay(1000);
         digitalWrite(green, LOW);
         delay(1000);
       } else if(sequence[i] == 2) {
         digitalWrite(red, HIGH);
         delay(1000);
         digitalWrite(red, LOW);
         delay(1000);
       } else {
         digitalWrite(blue, HIGH);
         delay(1000);
         digitalWrite(blue, LOW);
         delay(1000);
       }
    }
    level += 1;
  }
}

You're using the Uno? Your array sequence with 1000 entries eats up 2,000 bytes of RAM. (To say nothing of your other variables.) It might be causing some issues.

I have no problems running your code on my board, of course I changed the sequence array to have just 100 entries. Maybe that was a problem?

@lemontwistI changed the 1000 to 100 and now it runs as expected. Guess it run out of memory and removing the extra code freed some up?

Probably was the case. Memory management is very important. Microcontrollers have much more limited memory than PCs!

I will add an official answer just so that others can see it if they run into similar problems.
The issue is with the int sequence[1000] array, which eats up 2,000 bytes of data memory. The Uno only has 2,048 bytes of data memory so the instability is due to this memory hog of an array. Use a smaller number of array entries or switch to char (if you can) to use half the bytes of an int.

Compiler output:   Sketch uses 1724 bytes (5%) of program storage space. Maximum is 32256 bytes.
Global variables use 2017 bytes (98%) of dynamic memory, leaving 31 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

offtopic (but cannot put it in a comment):
I do not see any problem with your code (maybe it's in the circuit?)
You can rewrite the 10 s pregame flash as:
// Pre Game light flash
setAllLights(HIGH);
setAllLights(LOW);

void setAllLight(int state)
{
  digitalWrite(yellow, state);
  digitalWrite(green, state);
  digitalWrite(red, state);
  digitalWrite(blue, state);
  digitalWrite(debug, state);
  delay(10000);
}

You can even optimize this further by creating an array:
int[] lights = { yellow, green, red, blue, debug}

void SetAllLights(int state)
{
   for (int color = 0; color < sizeof(lights) / sizeof(int); color++)
   {
       digitalWrite(lights[color], state);
   }
}

You can rewrite the inside of the loop like:
switch (sequence[i]):
   case 0:
      flash(yellow);
      break;

   case 1:
      flash(green);
      break;

   case 2:
      flash(red);
      break;

   default:
      flash(blue);
      break;
}

void flash(int colorPin)
{
   digitalWrite(colorPin, HIGH);
   delay(1000);
   digitalWrite(colorPin, LOW);
   delay(1000);
}


text:
MIDI and DMX together
I am fully new to Arduino (even don't have one ... yet), however, I'm looking into possibilities to use both MIDI in/out and DMX together. If I understand correctly the MIDI library (re)uses the UART/COM while the DMX does the same.
I am wondering if it can be used together (e.g. use MIDI in to control MIDI out and/or DMX out).
(Also still checking if I would need some simple MIDI/DMX components or 'full' MIDI or DMX shields/boards.)

Here's a web page I created with photos, code, and detailed instructions: http://lights4music.com/instructions.html

@Lights4Music Thank you very much .... because of memory usage I decided to move to STM32, but later when I also want DMX I'm sure I can use some of the information of your project. Cool project you have btw. and thanks for the link!

Yes you can use multiple UART/Serial devices with a single Arduino.
However, there are some things to consider:
The Arduino Uno supports a single hardware serial connection (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.
The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.
Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.

note that since DMX needs 250kbps and MIDI uses only 31kbps, the MIDI should be the software one...

Thanks for the answer and note, this is very helpful ... I guess I have to get used to Arduino, and maybe buy a starter kit to test if a software MIDI Serial solution would work well enough. Just wondering if I can use the hardware serial connection for debugging another way but I will add a new question for that.

The DmxSimple/DmxMaster library does not use serial and will work simultaneously with the MIDI library by 47 Effects.  I have used the Sparkfun MIDI shield with the Tinkerkit DMX shield.  The trick to stacking them is using tall headers on the MIDI shield and not soldering the XLR connectors on the DMX shield.
Or you can use a Teensy which has multiple hardware serials and more RAM at a good price but requires building a couple basic circuits.

Thanks for the answer, good to know both MIDI and DMX can be used.


text:
Arduino Mega and LP621024D70LL
I'm intending to try a LP621024D70LL (128 KB SRAM memory, 32 pins) on an Arduino Mega.
However, I now see there is no library for it ... I wonder how hard it is to access it? I can miss 32 digital pins (the Mega has enough), however, I'm a bit worried about having to write a library, especially since I do not have any gear like an oscilloscope.
Would it be easy to use the library of the more knwn 32K256 or 23LC1024 as basis? (where I also have no experience with btw).

That's so old I can't find a datasheet for it. If you know the pinout then you know more than me at the moment. Chances are it's a standard 8-bit CPU interface.

Writing:

Set the address on the address pins, set the data to write on the data pins, enable the chip, and pulse WR.

Reading:

Set the address on the address pins, enable the chip, and while pulsing the OE pin read the data pins.
And no, you can't really use a serial SRAM chip library as a basis - the operation is completely different.

http://www.allcomponents.ru/pdf/amicc/lp621024d70ll.pdf

Thanks ... well I have the datasheet: http://html.alldatasheet.com/html-pdf/55651/AMICC/LP621024D-70LL/133/1/LP621024D-70LL.html
Doesn't seem to complicated what you write :-) Going to give it a try ... and if I succeed I will make it public for everyone if interested.
Didn't know it as old, but I guess it doesn't matter.

Yep, it is as I described. It has two chip-enable pins, one has to be high and the other low to enable it (you can probably tie them both permanently enabled since you aren't sharing the bus) and just toggle the OE or WR pins.

No one much uses parallel SRAM chips any more. They are quite rare new.

Thanks for the extra explanation ... and I understand the 23LC1024 has less ins, but works more complicated (although with a library it isn't a problem). But besides it is a bit cheaper, the main reason is I'm just getting into electronics so 'back to the basics' is maybe not so bad after all.

This kind of chip is best used with a small MCU. Something like a 6502 or a Z80. Use it to build your own computer from discrete ICs ;)

(I also ordered a 23LC1024 so I can try both... 6502 sounds cool to (I remember it was the heart of the Commodore 64).

And many other systems too. 4 things are all you need: a 6502, some SRAM (you have), a parallel Flash chip, and some form of IO interface. Oh, and some way of getting code onto the flash chip. And there's your computer.

Let us continue this discussion in chat.


text:
Advanced ADC setup on Due (SAM3X8E) to increase precision
I want to make some precise measurements with Arduino Due. Although I'm using very good external voltage reference (LTC6655) measured data is still jumping around, especially significant when I'm trying to measure low voltages (0.1-0.05V). Can I improve ADC accuracy by changing it's settings?
The default Arduino Due ADC settings are:
// Initialize Analog Controller
pmc_enable_periph_clk(ID_ADC);
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
adc_disable_all_channel(ADC);

So, with adc_init we can configure frequency and startup time. And with adc_configure_timing we configure tracking time, settling time and transfer time. But how to select those values? Does increasing of that times improves precision?
Useful links:
Datasheet - ADC description starts on page 1317.
Atmel Software Framework - see adc.h and adc.c.

What are you measuring? Is it possible that it's intrinsically variable (jumping around)?

@Squats, I'm measuring battery voltage.

@LookAlterno, It's an old question and I don't remember exactly. Something about 10-20%.

Generally speaking the input BandWidth of the analog signal is a major cause of noise in a ADC circuit as well as improper ground and reference generation and layout techniques.  Be very careful that ALL of the analog paths do not have any digital current return paths. Remember that at 12 bit for a 1.25V reference an LSB is ~300uV. I have not ever measured the SNR of the SAM ADC but I doubt that it is the specified ~60db (i.e. 10bit) unless absolute care is taken during the layout/routing.
Recommend:
1) Limit input BW to the correct channel ground. (well below Nyquist BW if possible to avoid alliasing)
2) Oversample if possible.
3) Insure low digital I/O of peripherals during sample period.

measured data is still jumping around

it will always jump around -> that's why adc modules are such a great random number generators (using its lsb). jumping around 8 - 9 lsb isn't that rare. anything beyond that should be investigated.
a few things to watch for:

use a good reference;

allow sufficient time;
pay attention to layout;
make sure that the source impedance isn't too great;
put a signal conditioning circuit on the input. a 1k/.1uf filter can do wonders;
pick the right oscillator for the adc module - see some c8051f350 code for example;
write the right code;
oversampling.

Thanks for broad answer, but my question is about ADC setup on SAM3X8E.

I've found http://sim.okawa-denshi.jp/en/CRlowkeisan.htm to be useful for designing a low pass filter but make sure you're not sampling more frequently than the design of the filter.

Default resolution is 10b because of backward compatibility, so you can start with setting analogReadResolution(12); as stated on Arduino analogReadResolution Refference page.
If it's still not enough you can use GAIN setting for used ADC channel. For single ended input GAIN can be set up to 4. But it means you can mesaure voltages up to 1/4 of Uref

I think increasing the resolution will not improve actual precision. It just will add more trashy bits which has nothing common with real measured value. I decided to use external ADC.

@kelin - the degree to which increasing resolution increases precision depends a lot on how clean the analog circuit design is, of the board and the source, and even on how much "is going on" digitally at the time of reading - sophisticated designs often shut a lot of the chip down while taking sensitive readings.  Also, even "noisy" bits can yield precision if evaluated statistically, for example putting many readings into a filter.


text:
Interrupt and delay problems on Attiny 85
I wrote this code and uploaded it to attiny85:
 int hours = 2;
 int minutes = 4;
 static int MINUTES_COUNT_BIT = 5;
 static int HOURS_COUNT_BIT = 3;
 #define button 2
void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(button,INPUT);

  attachInterrupt(0,pin_ISR,CHANGE);

}

void loop() {

  // put your main code here, to run repeatedly:

}

void pin_ISR(){
    if(digitalRead(button)==LOW){
      for(int i = HOURS_COUNT_BIT;i>=0;i--){
      byte act_bit = bitRead(hours,i);

      switch(act_bit){
        case 0:
          digitalWrite(3,HIGH);
          delay(1000);
          digitalWrite(3,LOW);
          delay(1000);
          break;
        case 1:
          digitalWrite(4,HIGH);
          delay(1000);
          digitalWrite(4,LOW);
          delay(1000);

          break;
        }

    }
  }

  }

When I click button it lights up LEDs but it is so much faster than 500 milliseconds it looks like that:
https://drive.google.com/open?id=0ByeWvrEgy2gRNUp3MDNxQTAxd2c
Please help

Maybe you did not Burn Bootloader with the same MHz setting as you uploaded the Sketch.

Delay in an ISR?

In short:

Arduino delay() is relying on millis().
The millis() function is  updated by timer ISR.
ISR handler blocks all other ISRs by disabling global interrupts.
No update for millis results into deadlock in delay if you use it in another ISR

And recommendation for ISRs? Do it as short as possible! Set some volatile flag and do the action later outside of ISR.


text:
Is Arduino uno SPI comunication can be also master and slave in the same time?
Is Arduino uno SPI comunication can be also master and slave in the same time?
OR master 2 slaves in the same time?
I want to recevice data from a sensor and display on OLED (all data transfer with SPI bus)
Can I master those two device (sensor & OLED) in the same time? (with SS pin to select slave )
OR Can I be both slave(recevices the data from sensor) and master (sent data to OLED) in the same time ?
What should I do ? and How can I do?
(I read the SPI example code on the Official website , but I still have no ideal about it)

See my post about using SPI on the Arduino

You can have several devices on an SPI bus. Each must have a chip select. The Arduino SS pin (Uno pin 10) is often used for chip select. Chip select pins should then be in output mode.
Connect the sensor and display to the SPI bus (MOSI, MISO, SCK) and use a chip select pin for each.
A driver (library) for a device connect to the SPI bus will typically assert the chip select pin and transfer commands and data. The SPI transfer is both read and write at the same time.

Thanks a lot for your rely.  !! Do you have any reference code or example code ...I still have no ideal about how to implement.

Start by reading this tutorial. https://learn.adafruit.com/monochrome-oled-breakouts/wiring-1-dot-3-128x64

SPI is bi-directional, so sending data or receiving data doesn't indicate if it's a master or a slave.
The master is the one that initiates the communications, that's all. So the arduino is a master in both cases. The master send data to the OLED. The master requests data from the sensor.

Thanks a lot about your answer ! I got it.  But can I ask you more about this condition ? What example code should I read,I still  have no ideal about how to implement this system.


text:
ESP8266 Aes encryption using Arduino IDE
I'm trying to implement an AES encryption function on my ESP8266 controller, using Arduino ide and this aes library.
I finally made it work after many attempts but the output i get from the encryption function is only numerical and it doesn't correspond to other encryptions made by other softwares.
This is the code part relative to the AES encryption:
 #include <AES.h>

AES aes ;
byte *key = (unsigned char*)"0123456789010123";
unsigned long long int my_iv = 36753562;
 tempToken = RANDOM_REG32 % 10000;
    randomstr = String(tempToken);
    //answer = "{\"token\":\"" + randomstr + "\"}";
    byte plain[4];
    randomstr.getBytes(plain, 4);
    Serial.println(randomstr);
    Serial.println(plain[0]);
    Serial.println(plain[1]);
    Serial.println(plain[2]);
    Serial.println(plain[3]);
    byte cipher [48];
  //  aes.iv_inc();
    byte iv [N_BLOCK] ;
    aes.set_IV(my_iv);
    aes.do_aes_encrypt(plain, 48, cipher, key, 128, iv);
    String ciphertoken = "";
    for (int i = 0; i < 48; i++) {
      ciphertoken += cipher[i];
    }
    answer = "{\"token\":\"" + ciphertoken + "\"}";

It basically generates a random number between 0 - 9999, then converts it in a byte array (because aes function needs a byte array as input), then encrypt this byte array and prints the output, written in cipher byte array.
This is the output I get from it
6188
54
49
56
0
{"token":"521111513725521540120674957151112223103194250224197251261938514437131212302201813929189123134524113912554682501508415421130220"}

I can't understand if I did something wrong of if it is formatted in a strange way and if I can get the right encryption from it

Could you replace your code with a minimal, complete and verifiable example (http://stackoverflow.com/help/mcve) please (remove the random part - use a well-defined input for this purpose), as well as the output you expect?

I don't know whether this is the only problem, but the way you are building up the string is bad: you are appending the decimal value of each byte of the cipher - so if your cipher array were, say, { 0x52, 0x11, 0x115, 0x137, 0x255, 0x215, 0x40, 0x1, 0x20 .... } you'd get the string you're getting: 521111513725521540120...  That's probably not what you want.
Probably what you want for that part is to base64-encode cipher, which you can find out how to do, for example, here.  (If you see encrypted stuff in printable format, usually it's base64 encoded.)


text:
Arduino-ESP8266 socket
I am programming an ESP8266 module via Arduino IDE. I basically have to use it as a server that can light up a led when a client sends a request.
This is okay but I have to implement it with a NONCE and AES encryption system to prevent replay attacks. My problem is that my esp server has to send a value to a client but I only saw the ESP as a data receiver and I can't send custom strings.
This is my code but it does not work because I have problems with the serverClients[i].write(randomstr,4); function
I highlighted the non working part of the code
#include <ESP8266WiFi.h>

#define RANDOM_REG32  ESP8266_DREG(0x20E44)
#define MAX_SRV_CLIENTS 3
const char* ssid = "********";
const char* password = "********";

WiFiServer server(7000);
WiFiClient serverClients[MAX_SRV_CLIENTS];

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
delay(5000);
Serial.print("\nConnecting to "); Serial1.println(ssid);
server.begin();
server.setNoDelay(true);
Serial.print("Ready! Use 'port ");
Serial.print(WiFi.localIP());
Serial.println(" 7000' to connect");
}

void loop(){
uint8_t i;
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
continue;
}
}
//no free spot
WiFiClient serverClient = server.available();
serverClient.stop();
}
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
while(serverClients[i].available()) Serial.write(serverClients[i].read());

//THIS IS THE NON WORKING PART
long randNumber = RANDOM_REG32 % 10000;
 Serial.println(randNumber);
String randomstr = String(randNumber);
 serverClients[i].write(randomstr,4);
}
}
}

if(Serial.available()){
size_t len = Serial.available();
uint8_t sbuf[len];
Serial.readBytes(sbuf, len);

for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
serverClients[i].write(sbuf, len);
delay(1);
}
}
}
}

I guess I have some problems with char arrays, strings, etc... but I can't make it work

What is the output of while(serverClients[i].available()) Serial.write(serverClients[i].read());?

It displays infos of the connected client like for putty it says SSH-Putty etc...

Does if(Serial.available()) { ... work as expected? Are the clients receiving the data read from the serial port?

You didn't say the non working block doesn't compile. If you had mentioned that I would've probably given you the solution a few minutes after I saw the question.

Replace the non working code with this and it will compile:
long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
size_t length = 4;
char randomstr[length];
itoa(randNumber, randomstr, 10);
serverClients[i].write(randomstr, length);

I've just noticed and corrected a mistake in my code, it should be itoa(randNumber, randomstr, 10);, not itoa(i, randomstr, 10);.


text:
How important is the INT pin of the MPU6050 (GY-521)?
I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking website or in the picture below:

as you can see in the picture above the INT pin is used.
I then wearched for a way to wire multiple MPU6050 to an arduino using a multiplexer and I found a way on horizonlab's website or see the picture below:

As you can see in the second picture the INT isn't used at all. I'd like to know how important it is and what I'm missing out by not using it.

You are connecting a 3.3V sensor to a 5V Arduino board. That means the I2C signals are not fully compatible. With many modules and each module having a pullup resistors from SCL to 3.3V, that might be too much. What is the value of the pullup resistors on the MPU-6050 module ? What sample rate do you want to achieve ? Can the Arduino Uno handle all that data ?

@Jot the two resistors next to the SCL say "222". I'm not sure how to calculate the sample rate I want to achieve but I would like to read each module at least 60 times per second (at most 120 times per second). Can the arduino handle that much data? I hope so. Otherwise I'm gonna have to add an SRAM to the circuit or use a second arduino and a third and so on and divide the MPUs between them until they all can handle the data.

The 222 means 2k2. That is a low value. The maximum current is specified as 3mA. Since those 2k2 are tied to 3.3V, the current is 3.3/2k2 = 1.5mA per module. When you want more than two modules, you have to desolder the pullup resistors. You also need a I2C level converter. The Arduino Uno can not do that many modules at that high datarate. Sorry. It doesn't even come close. Beside that, the total length of all pieces of wire of SCL and SDA can be 50 cm. That is the rule of thumb, only 50 cm.

@Jot 50 cm that's short. Is there no way to extend the length of the cable. (I can still work with that by using more arduinos. I just feel like it's a shame it can't be longer)

That's the rule of thumb. Some say they can get up to 3 meters, but that has a lot requirements for: the kind of wires or cable, the pullup resistors, the voltage levels, the i2c clock speed, and so on. Could you add to your first question what kind of project it is ? How many sensors ? How far apart ? Cost restrictions ? If you want to use many Arduino boards, how will you connect them to a computer ?

I'd rather not mess with the question right now. In my experience changing the scope of a question makes people mad. I'll ask another question if I encounter any issues next.

I'm using mpu6050 with 5v, using few of them at once without disordering any resistors. Most of the time keep them on for quite a long each tome. It never fried anything for me. Also my wiring is much longer than what you're saying. 50cm are you kidding me? I've connected 2 of them in a single old cat5 that is way much longer than that.

The INT is the interrupt signal, usually open-drain output and you can connect many of them to the single MCU interrupt line (but you have to check all devices which ones are ready). The LOW level from MPU device signalize that data are ready (conversion was finished). So you don't have to periodically read status register to find it out (no polling is necessary).
In short, using INT is optional.

At first level they are optional, and at least half the code out there if not more never uses them.  If you do connect them together, then you have to poll all of them to see which is ready.