text:
Arduino Object Array initialization
I just got an Idea of trying to code rain simulation with arduino and Adafruit OLED display. When I finished it was quite messy code so I thought That maybe doing it Object Oriented would help. This code is just a sketch that MAYBE works. The thing is that I need to create an array of objects(drops) and then display them. I have tried to display just one drop and it does not seem to do anything, even Serial wont print the pos_y. I have never wrote an Arduino code with objects so I just made a quick research and tried. here is the code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

class Drop{
  private:
  int pos_x = random(0, 128);
  int pos_y = random(-5, -20);
  int len = random(3, 7);
  int speed = random(6, 13);
public:
 void fall()
{
 display.drawFastVLine(pos_x, pos_y, len, 1);
 pos_y = pos_y + speed;
 delay(5);
 Serial.println(pos_y);
 display.display();
 display.clearDisplay();
}

};

Drop* drop = new Drop[50];

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

void loop() {
  drop[1].fall();
}

I will appreciate any suggestion or solution, spent almost entire day doing this "simple thing"..

I tried your code using a dummy implementation of Adafruit_SSD1306 that just prints to the serial port. It seems to work as expected.

can the display show negative y position? becose it start with -5 (you don't initialize random)

Well, cutting out all the display code the program appears to work fine for me.

It may well be then that the display driver hates a negative Y value. Not using that library ever I can't say...  Personally I'd never use an Arduino for anything to do with a display...

do you have 9600 baud set in Serial Monitor? add some prints to see where the code hangs

The code works without the display commands. A problem could be that you start with negative pos_y and use it as parameter for drawFastVLine.
Function random returns first parameter if it is a larger value then the second parameter. random(-5, -20) always returns -5.
To have more random random values, you should call randomSeed in setup().
And you can use global array Drop drop[50];.

I dont think so, the messier version without objects worked fine with negative values :/ And thank you for the clarification with random!

Okay i just used Global array and it seems that it fixed the problem ;). Thank you!

strange. what version of IDE you have. is in Question the same sketch you use?


text:
NodeMCU ESP8266 12E loses code after power is reconnected
I have uploaded a simple code to control a 8 channel relay by turning individual relays on and off
When I upload the code it works properly, the code works properly and the relays turn on and off in the desired pattern. However when i disconnect the USB cable from my computer and reconnect it, the code isnt working anymore, there is no visible action happening. Is the code erased from memory after power is cut?
int pins[] = {D0, D1, D2, D4, D5, D6, D7, D8};
int i;

void setup()
{
  Serial.begin(115200);
  for(i=0;i<8;i++)
  {
    pinMode(pins[i],OUTPUT);
    digitalWrite(pins[i],HIGH);
  }
}
void loop()
{
  for(i=0;i<8;i++)
  {
    digitalWrite(pins[i],LOW);//Turns this relay on
    Serial.println(pins[i]);
//Turn the previous relay off
    if(i==0)
    {
      digitalWrite(pins[7],HIGH);
    }
    else
    {
      digitalWrite(pins[i-1],HIGH);
    }
    delay(700);
  }
}

My circuit:
NodeMCU | Relay
D0 IN1
D1 IN2
D2 IN3
D4 IN4
D5 IN5
D6 IN6
D7 IN7
D8 IN8
Vin VCC
GND GND

Your usage of D0 is forcing bootloader mode to run on boot...?

@Majenko D0 is io16

Well, whatever random D number they decided to assign to GPIO 0 then.... Why couldn't they just number them what they are, rather than randomly assigning other numbers to them?

I had the same issue and solved the problem by the following link : https://github.com/esp8266/Arduino/issues/1074#issuecomment-258669539

D3 (GPIO0) and D4 (GPIO2) both need to be high on startup for the user program to be executed. The relay board connected to those pins are preventing a sufficient high on those pins.
If you need to use those pins then try using a stronger pull-up resistor on those pins. Try 330-470 ohms.
Either that or you will need to add additional circuitry between the port pins and the relay driver. Also please be aware that this will place a high on the relay driver input and will try to turn on the relays. Your powerup conditions may not be what you expect.

Your code will block the loop for more than 5 seconds. For the NodeMcu I found that if the main loop is delayed for long time strange things will happen. So you may also try refactoring to get rid of the for loop and using a simple counter to toggle the relays in each iteration of the main loop. so that your main loop will only be blocked for less than a second.

source: Stack Exchange

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

sort: votes


text:
Communicating with a 12V device?
I'd like to connect a 12V access control device to the Arduino, but I lack the understanding.
How can the signals from and to the device be done when they have different voltages?
I am afraid that the 12V would brick the Arduino.

Opto-isolators are your friend here...

D0 an D1 are weigand26 for external reader. it should be 5 V

@Juraj Interesting. I can't find info on this, and the vendor doesn't understand my question. I guess I'll just buy it and measure it myself.

where do you see that this version has D0 D1 pins?

@Juraj I'm sorry, I linked the wrong one. I fixed the link. Here it is here as well.

here is the info about weigand26  https://www.dhgate.com/store/product/rfid-proximity-entry-door-lock-access-control/168634282.html

@Juraj Hmmm, I don't see the D0, D1 pins on this one. Are they labeled differently?

down on the page is a table. it mentions it as option. it is input only for additional reader

@Juraj Yes, I saw the table. I was talking about the pictures, as they don't have those pins.

You could use an opto-coupler:

An opto-isolator (also called an optocoupler, photocoupler, or optical
isolator) is an electronic component that transfers electrical signals
between two isolated circuits by using light. Opto-isolators
prevent high voltages from affecting the system receiving the
signal. Commercially available opto-isolators withstand
input-to-output voltages up to 10 kV and voltage transients with
speeds up to 25 kV/μs.
A common type of opto-isolator consists of an LED and a
phototransistor in the same opaque package. Other types of
source-sensor combinations include LED-photodiode, LED-LASCR, and
lamp-photoresistor pairs. Usually opto-isolators transfer digital
(on-off) signals, but some techniques allow them to be used with
analog signals.

Here is an example schematic and packaging:

If you have a heavy load (although this does not seem to be your case) then they can also be used in conjunction with relays - here is an eight channel opto-coupler relay module board:

I see. So the way this would work is:

12V power to the access control.
5V power to the Arduino.
A wire from the D0, D1 pin on the access control, to the opto-coupler, and a wire from it to the Arduino in a digital pin.

Is this correct?

@Majenko Can you please tell me if my comment above is accurate?

An opto-coupler is like an LED on one side and like button on the other. You treat it pretty much like those items.

On the input side of the board, connect an Arduino output pin to the the input of one of the opto- or relay inputs. Connect the Arduino Ground (and +5v if the board calls for it) to the respective board inputs. On the output side of the board, If the access device just needs a contact closure, connect those two device connections to the Common and Normally Open contacts of the same opto where you connected the Arduino pin. Or if the device needs switched 12v, Connect +12v to the Common contact and the device's switched input to the Normally Open contact.

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


text:
Serial.write is synchronous
I have a good experience of the real(/critical)time world, but I'm new with Arduino.
I noticed that Serial.write is synchronous. If the buffer size is >64 (the USART size) it lasts the time of the physical transmission minus 64char.
It is obvious with simple tests as : Serial.write (char64) comes back in 1 millisec if the USART buffeur is empty and comes back in 64*10/baudrate if USART buffer is full.
Does anyone has written an asynchronous Serial.write?
If not who can help me to write it? That is to say have the docs on the USART, the interrupts and soon? Basically, the point is to fill the buffer, get an interrupt when it is free to fill it again.
Thanks for contacting me.

you can test before write with availableForWrite()

Until the buffer is full, Serial.write is asynchronous.  You just have to avoid filling the buffer up.
Fortunately, there is the function Serial.availableForWrite() which returns the number of bytes available in the buffer. You can use that to see if there's room in the buffer for what you want to send, and if there is then send it (i.e., just placing it in the buffer).
By re-writing the UART handing to call your own interrupt routine to send a byte as and when needed you are basically doing exactly the same as the Arduino's HardwareSerial class is doing - just with your own buffer instead of the one in the HardwareSerial class.
There is no hardware buffer in the Arduino. It only has a single byte shift register for sending UART data. Any buffering has to be done in software, so either you implement that yourself, or use the existing buffering, or only ever generate and send one byte at a time, which is fairly useless.
If you really want to re-write it then all the information you need is in the datasheet for the MCU on your chosen development board.

The terms "synchronous" and "asynchronous" when applied to situations like this are better replaced with "blocking" and "non-blocking", since "synchronous" and "asynchronous" when applied to serial communications imply different styles of data transmission, not software implementation.

Thank you for your answer, very clear and very helpful.
Based on it I will use both of your suggestions :
1 Test first before write.
2 As the buffer size is software, extend it from 64 to 85 to be able to send a NMEA0183 phrase at once, and only wait if the next comes to soon.
I agree synchronous/asynchronous can be miss-understood because of data transmission protocol. But you get it!

I checked, the HardwareSerial.h starts with #if !defined(SERIAL_TX_BUFFER_SIZE) that is to say it can be defined outside before (just what I need). But where shall I place my #define SERIAL_TX_BUFFER_SIZE xx ? Is it in the Arduino Sketch itself or in some .h file? If this size is >256 a special mode is used. Does it improve performances or not? I guess each Serialx (on Mega) has its private TX and RX buffers. Have all the TX buffers the same size? Or shall I adjust each? Thank you in advance.

I believe they are all the same size. You want to place the define at the top of the HardwareSerial.h file so that HardwareSerial.cpp etc pick it up.

Thanks to Majenko I have the pieces of a gloabal solution. I just summaries and share :
The Serial.availableForWrite() gives the available space left free in the Serial TX buffer.
It your string is shorter the Serial.write will be passing, if not blocking (until enought free space).
You can adjust the size of this TX buffer (default is 64) in HardwareSerial.h. Take care buffersize larger than 256 (255 available) result in a longer processing time for Serial.write.
If you have Serial, Serial1, ... the size will be the same for both and ofcourse the buffers are seperated.
I noticed thas Serial.flush is blocking long (80ms). This is to take into account for time critical issues.
Enjoy

If you change the TX buffer size, please note that it should be a power of two. Otherwise the processing time for HardwareSerial::write() and the TX ISR will be much longer. The performance penalty for sizes larger than 256 is small in comparison.

Thank you for this Edgar. I've been throught the multiple layers of C++ code for the Serial.xx down to the HardwareSerial.xx. I wanted to implement a very simple and quick SerialTXClear to clear out the TX buffer queue, but I feel I'll miss layer. Where shall I find the doc on theses multiple layers?

I am not aware of any software layer other than the files you mentioned.


text:
Passive buzzer works with analogWrite(), but not with digitalWrite(). It also has constant static noise
I have a YL-44/MH-FMD passive piezo buzzer hooked up to an ESP8266/NodeMCU.
It's connected like this: Buzzer ---> NodeMCU
- GND ---> G
- VCC ---> 3V
- I/O ---> D2
This code makes a clear beep.
void loop() {
  analogWrite(BUZZER, 255);
  delay(100);
  analogWrite(BUZZER, 0);
}

This code makes a weird low clicking sound, no beep.
void loop() {
  digitalWrite(BUZZER, HIGH);
  delay(100);
  digitalWrite(BUZZER, LOW);
}

I have no idea why the second one doesn't work, as all the tutorials reference that one.
Also, why does the buzzer have a weird constant static noise and gets hot?
Am I doing something wrong in the wiring? I use no resistors, as the tutorials don't show that.

it is passive as you have in the title. it doesn't vibrate by itself. use tone() function. example is with basic examples in IDE

@Juraj Do you have any idea why there is static noise and it gets hot?

it is like a coil. under current it is pulled together. the click is the sound. 0 Hz :-) the noise is that it is not good to have it under constant current

@juraj Can you please explain how do I fix the constant noise? I don't see a way.

@Juraj I am using tone. It makes noise before and after the sound. There is no HIGH.

it is the WiFi. I set the pin as INPUT after the tone(). it makes it better

@Juraj Niiiiiiiice. Thank you so much Juraj, you are a hero! I am very new to this and you've helped me a ton.

YL-44 is active buzzer. you have something else

You haven't shown your setup() function. Did you forget to set the pin to OUTPUT when using it with digitalWrite()?

@Majenko I have this: #define BUZZER 4; and pinMode(BUZZER, OUTPUT); in setup.

To sound a passive buzzer, use Arduino tone() function. If you set the pin HIGH the piezo surfaces are pulled together (or pulled away). It is what makes one click but nothing more. To make a tone the input must oscillate at right frequency. PWM is one way how to do a beep. Use tone() function to generate tones of desired frequency.
Your analogWrite(255) is PWM at 1/4 of full on, because max analogWrite value on esp8266 is at default 1023. So it makes a nice beep with 255.
If you use a speaker or passive piezo with esp8266 you can expect noise generated by WiFi operations. I set the pin as INPUT after tone() to eliminate the noise.

But why does analogWrite work, and digitalWrite not?

analogWrite is PWM. oscillation or 'pulse train'. https://en.wikipedia.org/wiki/Pulse-width_modulation

On the ESP8266 analogWrite goes from 0 to 1023 not 0-255, so analogWrite(BUZZER, 255); is not the same as digitalWrite(BUZZER, HIGH);.  It's more like analogWrite(BUZZER, 63); on the Arduino.

@Majenko, thank you. I added it to answer

One thing to note about the digital write part.  While you have a delay between the HIGH to LOW, there is no delay to go back to HIGH (other than the time to leave loop and re-enter; which can be very small amount of time).
While on a slower processor (like AVR) this time maybe enough to cause some buzz (and consistent buzz), on the esp8266 its going to be fast enough that IO pin may not change state at all from LOW to HIGH.  On Esp8266, IO physical pin state is at a different frequency than instruction counts.  I believe its only 8 MHz.  Due to the time before a pin state change to take effect, changing back before it got around to changing the physical state may ignore that state change.  In the specific example, the LOW may get ignored often and you will have more random effects from that sketch.
Try adding another delay of 100 ms after setting the pin LOW.  this will simulate a PWM of 1000 ms on width of a 1100 ms duty cycle.
And even better, lower the delays by a factor of 100 (first being delay 10 ms, the new one a delay of 1 ms), you get a 10 (or so) Hz buzz.

Your code example does not work because you have a PASSIVE buzzer.  Your example would work okay with an ACTIVE buzzer.
With a passive buzzer you must turn on/off the digital I/O pin at the desired audio frequency.  Using the tone() API is an easy way to do this.
tone(BUZZER_PIN, 432, 250);   //  Play the buzzer at 432Hz for 250ms
Your buzzer is getting hot because it likely uses a PNP transistor to switch the coil on your buzzer module.  This type of transistor conducts when the input is LOW.  Some buzzer modules use NPN transistors and conduct when the input is HIGH.
To keep your buzzer from getting hot (and wasting current) set its input HIGH to turn it off (assuming it's using a PNP transistor which it sounds like it is based on your description)
digitalWrite(BUZZER_PIN, HIGH);
You'll need to do this after using tone() each time as it leaves the output pin LOW.
I recently created a discussion on this topic on AVRFreaks forum:
Buzzer Module gets Warm and Wastes Power


text:
Serial data not parsed correctly
The code I have works for the most part but when I send data via bluetooth received over software serial, too quickly, it is not parsed correctly.
I'm a bit stuck with what can be done to a void the incorrect formatting, since it works correctly if I send data slowly.
I could have a buffer to not send data more than once every set amount of time, but more responsiveness is preferred.
I am sending a string "center:255,0,255;"
it saves the command in a char array untill it sees the ":", then it saves the red in a  char array breaking on "," then same for the blue and green. when it  reaches the ";" it send the four arrays to print to a console. Later it the data will be used to light specific leds based on the command, but when I send data too quickly it gets parsed incorrectly, for example:
command: center
red:195
green:0
blue:255
command: center
red:208
green:0center:221
blue:0,255
command: center
red:246
green:0
blue:255

the 'green:0center:221' isnt correct, its either not seeing the "," or seeing the ";" too soon. Not sure how to avoid it.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  mySerial.begin(57600); //required when using the hm-10 with an arduino nano
  mySerial.listen();
}

void loop() {
  while (mySerial.available () > 0) {
    processIncomingByte (mySerial.read ());
  }
}

const unsigned int MAX_INPUT = 50;

void processIncomingByte (const byte inByte) {
  static int parse_the_string = 0;
  static char command [MAX_INPUT];
  static char red [MAX_INPUT];
  static char green [MAX_INPUT];
  static char blue [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (parse_the_string) {
    case 0:
      switch (inByte) {
        case ':':
          command [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            command [input_pos++] = inByte;
          break;
      }
      break;
    case 1:
      switch (inByte) {
        case ',':   // end of text
          red [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
       default:
          if (input_pos < (MAX_INPUT - 1))
            red [input_pos++] = inByte;
          break;
      }
      break;
    case 2:
      switch (inByte) {
        case ',':   // end of text
          green [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            green [input_pos++] = inByte;
          break;
      }
      break;
    case 3:
      switch (inByte) {
        case ';':   // end of text
          blue [input_pos] = 0;  // terminating null byte
          // terminator reached! process input_line here ...
          process_data (command, red, green, blue);
          input_pos = 0;
          parse_the_string = 0;
          break;
        case '\r':   // discard carriage return
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            blue [input_pos++] = inByte;
          break;
      }  // end of switch
      break;
    default:
      break;
  }
}

void process_data (const char * command, const char * red, const char * green, const char * blue)
  {
  // for now just display it
  Serial.print ("command: ");
  Serial.println (command);
  Serial.print ("red:");
  Serial.println (red);
  Serial.print ("green:");
  Serial.println (green);
  Serial.print ("blue:");
  Serial.println (blue);
  }

Set higher baud rate for Serial and in Serial Monitor. It slows down the processing and the mySerial buffer overflows.

thats embarrassing, how simple >_< Thank you so much


text:
Smaller and cheaper alternative to Arduino Uno for permanent projects
I have played a bit around with a Arduino Uno that came in a kit with a breadboard and components. Soon I would like to make some more permanent things.
I would prefer a smaller and cheaper unit than the Arduino Uno but that is almost as easy to use as the Arduino Uno, and very similar to use.
Is the Arduino Pro Mini 328 - 5V/16MHz a logical next step?
At 1/6 of the size of the Arduino Uno it is plenty small.
At 10 $ a piece the price is also good.
I understand that I must solder to get it to work. That should not be a problem.
Will I also need a USB serial board to program the unit?

next smaller with 328p is Nano

ATmega32u4 chips are also a good move (same as Leonardo) for 8-bit micro.  Coding is slightly different from UNO/328p (especially with serial), but you avoid the USB/serial converter.  Eventually, you can make your own PCBs and use the SMD chips, for a really compact project.

Pro Mini, 5V 16MHz Module With Crystal Oscillator ($2.18CDN): https://www.aliexpress.com/item/Pro-Mini-atmega328-Mini-ATMEGA328P-5V-16MHz-Module-With-Crystal-Oscillator-Pins-Replace-ATMEGA128-for-Arduino/32828645889.html. PL2303HX USB to UART adaptor ($0.70CDN):  https://www.aliexpress.com/item/FREE-SHIPPING-PL2303-module-USB-to-TTL-upgrade-nine-brush-board-PL2303HX-STC-MCU-download-cable/32592463585.html.

I think the first best choice is to remove the ATMega328p-pu chip from your Arduino UNO and incorporate it into your final circuit.
The chips are only about $1.50.
That way, you can just use your UNO as a programmer instead of the final device that you deploy.
I'm not sure why there isn't more documentation about the proper way to remove the ATMega328p-pu chip and using it on your breadboard, after completing your programming.
I explain exactly how to do this on my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone
But, here are the basics.
First you remove the chip.  It will look like the following after you do so.  (Note: I'm using the Elegoo clone of an UNO).

Next, you apply power to pin 7 and connect pin 8 to GND.
Need A 16MHz Crystal
But, the chip won't seem to run your sketch at this point.
That's because you actually need a crystal to run at 16MHz.
The UNO board has that chip installed and that is why it works.
You can see it here:

Finally you add the 16MHz crystal and a couple of 22pF caps and your chip will run standalone (no UNO).
You add the crystal to pins 9 & 10.  You can see all the details by reading my blog entry or reading the atmega328 datasheet.

Finally, Just Wire Everything Else Up
After that, just wire the rest of your circuit up to the proper pins and you can run your ATMega328p-pu standalone.
It's actually a nice learning experience too.
Just buy replacement atmega328p-pu chips for your UNO and you can create all the projects you want to for very cheap.

You'd be well served to add some circuit protection in there, since the 328p doesn't have any of it's own. Otherwise, this is a great way to go.

@SnakeDoc Thanks. And, I agree, any circuit protection is always advantageous. An interesting note: I had a circuit built on a cheap breadboard like the one shown, powered off an old phone charger and sitting on a shelf in my garage and running for over two years with no problems.  We even had a lightning strike that took out another item in the garage but my atmega328p-pu based circuit (bluetooth garage door opener) kept on running. Of course, I'm not advising people to build circuits like that but it is really cool that as a hobbyist we can do things like this.

You're missing a few wires in that last photo. Pins 20 (AVCC) and 22 (GND) need to be connected to VCC and GND.

@duskwuff, I believe that is only when you're doing DAC.  This is just a simple example to get someone started in the direction of using the chip as standalone.  I assure you the code to blink the LED in the sample does run.  Also, when I was starting out I created the circuit I mentioned in a comment above and I never connected AVCC and GND and the circuit ran for two years.  Of course, i'm not saying that will always be true.  Just mentioning the way the chip actually works. As always, check the datasheet for exact specs and especially if you experience something different.  Thanks.

@raddevus Refer to Table 28.8 in the datasheet: "AVCC absolute min/max: 1.8V/5.5V". Leaving AVCC unpowered is out of spec, and may cause damage. The GND pin on pin 22 isn't specifically associated with the ADC, and must be connected to GND.

@duskwuff I was reading over the datasheet and reminding myself too. I will keep that in mind and alter the doc soon.  Thanks  Edit - Wait where does datasheet say that leaving AVCC unpowered may cause damage?

@duskwuff also section 1.1.7 says, "AVCC is the supply voltage pin for the A/D Converter, PC 3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter." Notice the use of should instead of must. Interesting.

@raddevus Again, table 28.8 specifies an "absolute min/max" voltage. Absolute limits always carry an implied risk of damage if the limits are violated.

@duskwuff Thanks for the enlightening discussion. I agree with what you are saying and will change my docs and circuits soon to insure that is always connected.  FYI - I started working with ATMega328p-pu via the fantastic book AVR Programming : Learning to Write Software For Hardware (https://amzn.to/2PS9OOA) and in those first circuits the author, Elliott Williams, does not hook up those pins either. I think I was influenced by that.  The book really is great though and the author is knowledgeable. Thanks again, great discussion.

Why is there no bypass capacitor on the power pins in the breadboard picture? That is an absolute must. As close to Vcc and Gnd as possible.  Hey, but it is the Internet. Anyone can publish what they want.

@reddevus. To be more precise, the crystal that you indicated in the red box in this answer is the crystal used by the microcontroller handling the USB communication, and not by the ATmega328p-pu chip. You can see from the Uno schematics that the ATmega328p-pu chip actually uses a resonator: https://www.mouser.com/ProductDetail/Murata-Electronics/CSTCE16M0V53-R0?qs=HPA2Xx%252BU0WhPWbRcNuzhZw%3D%3D

@Kavka That's great information.  Thanks for adding.

Check the STM32F103C8T6 development board, cost about $ 1.5, and is faster/has more memory than the Arduino Uno, and is much smaller.
It can work with the Arduino IDE, but not all libraries are supported, so check before you want to use it if your used libraries are supported, or if there are different libraries you can use instead.
Update
Differences:
                       Arduino Uno       STM32F103C8T6 Mini Dev Board

MicroController            Atmega328P           Cortex M3
MIPS/MHz                        1                   1.25
Operating Voltage [V]           5                   3.3, most pins 5V tolerant
Input Voltage   [V]            7-12               USB only
Input Voltage (limit) [V]      6-20                (USB)
Digital I/O Pins               16                   37
From them:PWM Digital I/O Pins  6                   12
Analog Input Pins               6                   10
DC Current per I/O Pin [mA]    20                    ?
DC Current for 3.3V Pin [mA]   50                    ?
Flash [KB}                     32                   64
SRAM [KB]                       2                   20
EEPROM [KB]                     1                    -
Clock Speed [MHz]              16                   72

I2C                             1                    2
SPI                             1                    2 (18 MBit/s)
UART                            1                    3
CAN                             0                    1
USB                             0          USB 2.0 FS 12 MBit
DMA                             0          7 channels (ATsP, SPI, I2C, USART)
RTC                             0                    1
CRC                             0                    1
Unique ID                       0                    1

Programmed by                  USB                 SWD Debug (around $5)

IDE                         Arduino IDE         Arduino IDE, CubeMX, ...
Libraries                      Many               Limited

Dimensions  [mm]            68.6 x 53.4           53 x 22
Weight       [g]               25                    ?
Price (cheapest)  [$]         2.50                 1.50

Note: as written earlier, despite the mostly better specs, not all libraries are supported. Also a programmer need to be bought (only once, cost about $5).

You can also avoid getting the programmer if you get the Maple Mini clones (same uC, almost same HW, but with a bootloader already flashed)

@frarugi87 Or you can use the builtin UART bootloader (activated by setting BOOT0 high) for initial programming.

The STM32F103C8T6 is a great part. But it still is only 3.3v. It isn't a drop in replacement for the Uno. Try to connect it to a 5v character LCD and you will have problems, if it works at all. (the LCD)

For my product, I went from an Arduino Uno:

to the Arduino Pro Mini:

Yes you will need a  FTDI cable for programming and serial coms to the PC, but providing you don't need coms all the time, you will only need the one cable to upload the program to each device. They can be found pretty cheap too.
However I notice that the Arduino Pro Mini is retired now, so it may be a bit harder to source (it is still available on AliExpress). So for this reason, I suggest that you instead try the Arduino Nano:

which has the added advantage of onboard USB, meaning you no longer need the FTDI cable for programming or coms.
The ATMega328P that is the processor of these 3 boards does not have native USB, which means that the board also needs to include the FTDI FT232RL IC that is used in the FTDI cable. Having this IC can add additional costs to your bottom line.
For a few dollars cheaper per device, you can use a microcontroller (such as the ATMega32U4) that has native USB coms (and hence you save on the FTDI IC). One such product is the Arduino Micro:

All of these boards mentioned are native within the Arduino Ecosystem and (apart from the retired Pro Mini) should be easy to source online or at your local electronics shop. Your Arduino Uno program will work for all of these alternatives - you just have to change the board in the Arduino IDE:

There is one more board that I would like to mention - the DigiSpark:

It is only suitable for smaller programs, is limited in some of its features and is not an oficial Arduino board. Having said that, there is plenty of Arduino support - and its cheap!

I like the Nano and the Pro Mini. I like to work with it on a breadboard with other modules. If there is more circuitry involved I found it much more convenient than using an Uno. There are faster processors but for a lot of projects the 16Mhz 328 is more than sufficient. And like the Uno, these two are 5 volt powered parts. Sometimes what you need to connect to doesn't work well with 3.3 volt processors.
The Pro Mini and the Nano with easily be soldered into 0.1" spaced "Veroboard" (or equivalent) If you don't mind buying cloned parts, the cost of a Nano and Pro Mini is only a couple of dollars. Buying parts off Aliexpress, or even Ebay, can save you a lot, as long as you are patient when it comes to delivery.
The module that I am now use most often is the ESP8266. It is a powerful WiFi platform that only costs a few dollars and has quite a mature Arduino framework. Often I use this as the only processor in the design. I have even used it as the basis for a data logger and completely ignored the WiFi capability. 20x4 character LCD, current/voltage measurement chip (INA219), and a SD memory card, powered by a 18650 lithium battery.
There are lots of good inexpensive options.

you might want to point out that ESP12 modules do NOT have .1" pin spacing, which is a bit of a nuisance. There are inexpensive breakout boards, but these are quite wide and hard to use with solderless breadboards. Other than that, they're pretty handy. For about $1 more than a bare ESP12 module you can get a Wemos D1 mini (clone) that is about as easy to use as an Arduino Pro Mini or Nano.

Where did I say to use the ESP-12? I didn't go into a lot of detail on the ESP8266 because that really wasn't the focus of the question. I thought it was worth mentioning since a lot of people are not familiar with it. I totally support people using the Wemos D1 mini platform. It is a ready to go solution unlike ESP01, ESP12, etc. USB to serial and an onboard regulator makes a big difference. But I still feel the Nano or the Pro Mini is the most appropriate answer for the person who asked the question.

It's hard to consider any atmega based system in 2019 in comparison to the ESP systems, so you might mention for $2 with an ESP8266 you get a 40MHZ processor, a full development board ( not a chip ), wifi, and USB-based programming and monitoring without any extra cables. And also mention the ESP32 systems, which are more expensive at $7 to $10, but contain two CPUs, a full RTOS, multiple MB of flash, adds BT to WIFI, and native USB support. Compatibility with Arduino is included, and even running the provided RTOS they include Arduino libraries.

The ESP8266 has a 160MHz processor. It is a great option but it does have limitations. It only has one A/D converter and a bad one at that. The digital IO pins also have quirks. Pull up resistors are on by default at power up on most. Three IO pins set the operating mode and special care must be taken. The ESP8266 also needs a decent power supply. With the ESP8266 there is a lot of code running in the background and your code must co-exist with it. I really like the ESP9266 but it is not a great general purpose microcontroller. The ESP32 is better but also with issues.

If you want to stick with using Arduino and it's toolchain, you can order just a bare ATmega 328p (the microcontroller at the heart of the Arduino Uno) and use it by itself!
They're fairly low cost ($1.50-$3.00 range) and are breadboard friendly. For a more permanent solution, you can solder them into a proto-board (perfboard), or even a custom designed circuit board once your design gets to that level.
Here's an excellent guide from the Arduino folks about setting up an Arduino on a breadboard, using only raw components such as the ATmega 328p. This design uses an external 16MHz clock crystal, just like an Arduino Uno.
If you're OK with using the internal 8MHz clock onboard the 328p, you can do away with most of the extra components and just run the raw chip like in this guide (using the Arduino Lilypad Bootloader instead of the default Arduino bootloader). This will save even more money!
Either way, you'll need an AVR Programmer unit, since there is no USB port built into the 328p. This will be the most expensive part of this setup, but good news is you only need one, and it can program any 328p's you need. They can also be used to program non-standard chips that are capable of being programmed over Serial Tx/Rx pins, such as the ESP chips (you just hand-wire them). Very useful to have one of these if you're serious about these types of microcontrollers.
ATmega 328p Microcontroller Chip
ATMega Pin Stickers
Perfboard
AVR Programmer

If you order your ATMEGA328P-PU with the boot loader already installed: https://www.ebay.ca/itm/ATMEGA328P-PU-DIP-28-Microcontrolle-r-With-ARDUINO-UNO-R3-Bootloader-or-Not/401232444724?hash=item5d6b513d34:m:mDLpPK1-t0vsiOhYFC4DDpg:rk:4:pf:0, then a PL2303HX USB to UART adaptor ($0.70CDN) will work to upload "code": https://www.aliexpress.com/item/FREE-SHIPPING-PL2303-module-USB-to-TTL-upgrade-nine-brush-board-PL2303HX-STC-MCU-download-cable/32592463585.html

I always found it odd that Arduino uses a special bootloader for programming instead of using the built-in programming interface.

@immibis not sure what you mean exactly, but the arduino bootloaders do a lot of things that make working with the arduino's (and Atmel chips) a lot easier, including resetting of pins, switching to external clock, handing-off to your code, etc. Without it, you'd essentially need to write your own... which would be a waste of time since for majority of cases, the stock Arduino bootloader does everything you want anyway.

@immibis I think it is much easier to have a serial port interface rather than a programmer interface from the PC. Moreover, especially at the beginning, I think (personal opinion) that they wanted a complete system on a board, and integrating a programmer on the PCB was much harder than writing a serial bootloader. Consider that the first arduino boards had a serial port (Arduino RS232), so only one programmer was needed to program a lot of them (they were used at school)

@frarugi87 that's probably true, but for real beginners, plugging in a USB cable and using the Arduino IDE to upload "sketches" is about as easy as it can be. I think they made the right move to make it super accessible, especially for those who have zero microcontroller experience.

There isn't a good reason to use the dip parts. The Pro Mini doesn't take up any more space and it is a lot less hassle. Maybe ten years ago it made sense to use a dip part when there wasn't cheap alternatives. But now with the inexpensive (dirt cheap) modules available it just doesn't make sense.

@Rudy If you want to do your own thing, make your own packaging, or layout, save power (prolong battery life) or just make it look more professional, using the raw chips is certainly a great way to go. Plus you'll learn a lot more in the process, which makes the end result even more of a benefit. You can also help ensure people don't mess with it by plugging into the USB port, or do your own voltage regulation stuff, such as a buck-boost or whatever. Don't dismiss using the raw chips just because you can buy a Pro Mini...

@SnakeDoc The compiler could easily add that code for you, like it already adds code for you.

@frarugi87 Makes sense for the RS232 version, for sure, but now they have a custom-programmed USB interface on-board!

"I would prefer a smaller and cheaper unit than the Arduino Uno but that is almost as easy to use as the Arduino Uno, and very similar to use." A dip CPU is NOT as easy to use as the Arduino Uno. You are putting your values into your answer and not listening to the person who posted the question.

@Rudy Have you tried it? (I haven't tried with this chip, but I've tried with different similar DIP uCs)

@immibis Tried what? I have been designing commercial electronic products for almost 35 years. I'm a hardware designer. I have recently started using the Arduino platform because I wanted to do my own projects at home and the Arduino IDE and all the libraries was the easiest to start with. At work I design the electronics and then pass it on to the firmware, then software, programmers. I have designed with many different chips. I have even made a product (my code) with a PIC part with 512 bytes of code space. Efficient.

@Rudy it's pretty darn easy if you keep using the Arduino environment. It's exactly why at least two of us here have made that recommendation, including the accepted answer! The Arduino toolchain is very mature - and as the OP advances, they can branch out into more flexible solutions such as PlatformIO etc, all while still using the Arduino libraries! Pretty neat.

@SnakeDoc As I have said above. I design electronics for a living. I can't put out a marginal design. Something that is going to only work most of the time. Industrial controls not consumer items. I think it is great that someone wants to learn. But the question asked was for a smaller cheaper unit that was easy to use. And I believe my answer fits that. The breadboard example in the picked answer shows the lack of knowledge of the constructor. And it disappoints me when I see someone learning from someone who is not ready to be teaching.

@Rudy To summarize everything you've said - You use premade boards because you're too tired after work to make one yourself, and you've already learned all there is about uC's so everyone else should just skip learning and use premade uC boards cuz reasons and cheap Chinese clones are definitely more reliable than a home-made uC board cuz more reasons. Sorry, but you sound pretty salty right now. OP accepted his answer. OP clearly is interested in assembling their own ATMega328p custom implementation, and will still use the Arduino tooling. It's wonderful, and no skin off your back.

Unless you happen to be making and selling Arduino Pro Mini's for a living.... hmm....

@SnakeDoc  Your summary you attribute to me is pure fiction. I think you need to read the Code of Conduct because you are not acting the way expected on this site. -  As I have already explained, the answer I provided was based on the original question asked and the requirements expressed. And if the person considers a new criteria then that is his prerogative.  My reason for using stable modules is most newbies do not have the equipment required to troubleshoot the issues that often will come up due to a lack of understanding about stable design. They have more than enough to deal with.

@SnakeDoc I thought you might be interested in this. https://www.esp8266.com/viewtopic.php?f=13&t=17514

@SnakeDoc  A problem for you.  I hope you can help. https://arduino.stackexchange.com/questions/57938/problem-with-arduuino-to-breadboard-mega8

Arduino Pro Micro clones are super cheap and all you need to program them is a normal micro USB cable. You will probably have to solder the headers to do anything useful. They are available in a 3.3V/8MHz and a 5V/16Mhz version.

ProMicro has a 3.3v processor. That can be a problem with some designs. It isn't a drop in replacement for an Uno. But it is an interesting part.

No, just as with the Pro Mini there is a 5V/16MHz and a 3.3V/8MHz version.

Sorry then, my mistake.


text:
How to concatenate a part of a string and convert then to a int?
Lets say I have
String myString="AR0236";

I wish to extract the number 236 and assign it to an int. How can this be done?
P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!

note: concatenate means join.... it is opposite of what you are trying to do, which is split

see https://stackoverflow.com/questions/40538792/remove-first-few-characters-from-a-string?

There's multiple ways.
The String class (which TBH you should avoid) has some useful methods:

substring - extract part of a string as a new string
toInt - convert a string to an integer

So you can join them together:
int val = myString.substring(3).toInt();

That's the easy way.  Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.
If you are avoiding String, as you should, then you are working with pointers.  For instance:
char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data

int val = atoi(myString + 3);

myString + 3 gives you a new string pointer to a location that is 3 bytes further up in memory from myString - which equates to where the start of your number is.  Then convert that portion of the string to an integer.
The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.

Thank you for your response. The first method works although with a bit of a delay. I wish to use the second and more efficient method but doesnt work if i pass a variable in the second argument of the strcpy. The string I want to convert is from the serial so I the the string is unknown. How would you get around this?

Start by reading the serial properly. Start here: https://majenko.co.uk/blog/reading-serial-arduino

Thank you! Your link was really useful and my circuit works as intended to :)


text:
ESP32 not seen by a network analyzer application in server mode
I have used the scan wifi and blink examples provided by Espressif,
they are both working on the ESP32 using arduino ide.
However, I can not see my ESP( the SSID and signal strength) in the list of detected wifi when searching for it using a network analyzer app  ( Net analyzer on android)
This was solved when I used the ESP as Access point.
In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?
why is the ESP32 Lolin getting hot only when it is in AP mode?
Thanks in advance

What do you mean by "see" it? And what NA app? Are you assuming it should be an AP by default? Have you programmed it to be an AP and broadcast an SSID?

Can't a client be seen by all? So the problem is that I need to make it as an AP? My point is to use the ESP as client on assets and make the access point know the position using its signal strength.

Only access points can be seen by stations. When connected you use other protocols (mDNS) to advertise services.

In Client mode the ESP is using the WIFI capability. But why it can
  not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.


text:
How to convert hex to ASCII
I am receiving bytes, converting them into hex and now I need to convert the hex to ASCII. Can it be done on an Arduino? Or do I need something else?
I am new to programming with Arduino.

Is this connected to your earlier question? It is not clear, what you mean. In your previous code you are explicitly sending an ASCII version of hex (human readable hex).

i am receiving bytes and then converting them into hex or displaying them as hex ,and now i want to display them as ascii , is that possible ? sorry for this maybe dumb questions but i want to learn.

Can you show your (relevant) code, the location where you want to convert it, and describe how the output should look like?

If you have a byte variable b, you can

write(b) it as it is. if it is ASCII code of a readable character, the Serial Monitor will display it as that character, for example for 65 it will printt 'A'
print it as decimal number with print(b). for 65 it will print "65"
print it as hexadecimal number with print(b, HEX). for 65 it will print "41"
print it as a number in other base with print(b, base), for example print(b, 2) will print 1000001 if b is 65 in decimal


text:
Assigning array variables to int variables
I need to control thousands of rgb leds.To make animations I want to assign led numbers(addressable led strip) to arrays.For example floor[2]room[14]=106 106 is the number of led,there are many floors and rooms.I want to change floor or room numbers with that way I will make animations.
  We can say its 92x30 pixel monitor.I tried to create list of floor and rooms but I couldnt make it.
  I'm new to programming,help please!
Solved with this way #define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Are the LEDs in floor/room sequence? I.e., is floor[2]room[15] going to be LED 107?

yes,exactly.every floor has 92 rgb,and there is 30 floors.

Your Arduino has more than 8 K or RAM, right?

yes I'm using arduino due.

I'm already controlling all of leds,but I couldnt calibrate them.

sounds like you need to check out these guys (and similar projects) https://makezine.com/2012/11/18/worlds-biggest-led-cube/

are the LEDs ordered? LED number 1 in first room on first floor, no 2 in second room on first floor etc and the last number in the last room on the last floor? or is the mapping more complicated?

LEDs are ordered exactly as you said Juraj.

and on every floor is a same count of rooms?

yes,92 pixel on every floors

You really don't need to maintain a list.
Just calculate the LED index from the location:
int room = 14;
int floor = 2;

const int rooms = 92;

int led = room + (floor * rooms);

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.
You could make a macro:
#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Then your LED number is just:
int led = LEDNO(2, 14);

Here's an example taken from your code:
void floorsup(){

  FastLED.setBrightness(brightness);

  for(int a=1;a<255;a+=40){
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
  }
}

but with this way I cant light up many leds at the same time

What does this have to do with how many LEDs you can light up at once? This just gives you an LED number. What you do with that is up to you. I would use it to set an LED colour in the NeoPixel library. I don't think you quite understand exactly what you want to achieve with this.

yes but if I wanted to light whole fourth floor its gonna be easy with assigning them number.

They already have a number. What do you want to "assign"?

okay its long but I'm gonna share my code,you will understand what I mean

You have absolutely no need for your array for that code. Most of it can be replaced with a couple of loops and the macro I show above.

I have used a chunk of your code (the longest most wasteful portion) to demonstrate how you'd use it. The code is now readable.

ahhh now I got it! yes its really such a shame I know,I make like that with hurry.Let me obligate  more your code.At the first time I thought I'm gonna identify with int all numbers.

ohh man you just save me from a lot of works :D now I dont have to calibrate leds with python,I saw from another programmer in my company at the other project with the array way,so I thought I should make like that way.But with your way its saving me from a lot of works..

I'm talking too much sorry but I have one more question.How can I convert any image to RGB color code arrays?For example from uploaded image I will get RGB color codes for 92x30 pixels.Is it possible with python?

I have no idea about python. If I were scripting it I would do it in PHP since it has image functions right there for you - however I never need to these days, since the latest beta version of UECIDE has it all built in.

Something like this would work:
#define MAX_FLOORS  92
#define MAX_ROOMS   30

struct floor_str {
  int Room[MAX_ROOMS];
} Floor[MAX_FLOORS];

You would then access an individual LED address like:
Floor[2].Room[14] = 106;

yes,I can take all led numbers from python on this format,but I wasnt know how to assign them.Thank you!

btw does it should be like struct floor_str {   int room[MAX_ROOMS];  floor[MAX_FLOORS]; } ?

No. You make a struct of rooms as an array and make an array of them as floors.

I already figure out with another way but I would like to learn your method also.Could you check your code again? its giving error.

The syntax was correct but 'floor' appears to be already defined as something else.  An easy solution is to use 'Floor' instead.  (edited the solution above)


text:
Cannot compile code from Arduino WIFI shield example
I'm trying to launch the piece of code in this Wifi example:
https://www.arduino.cc/en/Reference/WiFiConfig
via Arduino.cc online editor, but I'm getting those errors:
/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:87:24: error: 'PINS_COUNT' was not declared in this scope

and
/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:97:15: error: 'NINA_GPIO0' was not declared in this scope

Do someone has an idea of how to solve this?

Those kinds of errors are usually caused by the selection of an incorrect hardware in the IDE.
Choosing a correct board in the IDE will solve the compilation issue.
Since you said that you used the Arduino.cc online editor, I pasted your code into the editor.
You did not say which Arduino board or which WiFi module you are using, so I chose Arduino Uno WiFi board as a starting point.
Compiling the code produced the same errors as in the post.
Next I chose Arduino Uno WiFi Rev2 board, and compiled without errors.


text:
Can I use arduino to generate 8mhz frequency ultrasonic pulses in piezo discs?
void setup()
{
    pinMode(freqOutputPin, OUTPUT);
    Serial.begin(9600);

    // Set Timer 2 CTC mode with no prescaling.  OC2A toggles on compare match
    //
    // WGM22:0 = 010: CTC Mode, toggle OC
    // WGM2 bits 1 and 0 are in TCCR2A,
    // WGM2 bit 2 is in TCCR2B
    // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
    //
    TCCR2A = ((1 << WGM21) | (1 << COM2A0));

    // Set Timer 2  No prescaling  (i.e. prescale division = 1)
    //
    // CS22:0 = 001: Use CPU clock with no prescaling
    // CS2 bits 2:0 are all in TCCR2B
    TCCR2B = (1 << CS20);

    // Make sure Compare-match register A interrupt for timer2 is disabled
    TIMSK2 = 0;
    // This value determines the output frequency
    OCR2A = ocr2aval;

    Serial.print("Period    = ");
    Serial.print(period);
    Serial.println(" microseconds");
    Serial.print("Frequency = ");
    Serial.print(freq);
    Serial.println(" Hz");
}

void loop(){}

I am working on a project where i need an ultrasonic pulse of 8Mhz every one second and emitter is piezo disc. Please help me with the code.

If you are using an AVR-based Arduino, read Timers and counters, by Nick Gammon.

That's an interesting article, but it seems to be about detecting pulses, not making them. Did I miss something?

actually i need both emission and detection but currently i am working on emitting the pulses using arduino and piezo discs but i am not so good with coding

what code have you tried so far?

ive embedded the code above

@Danish and why it does not work? What does it do? What do you expect it to do?

With 8 Mhz pulse, I assume you mean a pulse of 0.125 µs duration every second. "Frequency" may be misleading here.
Since the ATmega328 in the Arduino Uno is only clocked at 16 Mhz, you only have one extra cycle before having to turn it back off. Debugging and developing at this sort of speed absolutely requires a good oscilloscope.
I would attempt setting your output pin via register, and then turning it off again right after. Use cli() to prevent interrupts during your desired pulse.
void setup() {
  DDRC |= (1 << DDRC0);   //Set PC0 as output (Analog Pin 0)
}
void loop() {
  cli();                  //Disable interrupts
  PORTC = 0b00000001;     //Set Analog Pin 0 HIGH
  PORTC = 0b00000000;     //Set Analog Pin 0 LOW
  sei();                  //Enable interrupts again
  delay(1000);            //Delay for 1000ms until next pulse
}

Beware that this would also set all other pins on Port C (Analog Pins 1 through 5) LOW.
This
  PORTC |= (1 << PORTC0);     //Set Analog Pin 0 HIGH
  PORTC &= ~(1 << PORTC0);     //Set Analog Pin 0 LOW

would be cleaner and only affect Analog Pin 0, but it may take more than one clock cycle to execute.
Unfortunately, I don't have a quick enough oscilloscope to try this out.
If it is too fast (e.g., you get a pulse of duration 0.06125 µs, you may want to insert another PORTC = 0b00000001; before turning it off again. It is not unlikely that compiler optimization might just remove this when compiling, so you may have to set some other register to waste that one clock cycle.

Your second snippet is the way to go. It is almost guaranteed to generate the proper sbi and cbi instructions at any optimization level (save, maybe, level zero). These instructions execute in two clock cycles each, thus you get a pulse exactly two cycles wide.


text:
If a condition is ever met I want to run a loop permanently
I am trying to run an LED to do SOS in morse code if a temperature is over 20 C and motion is detected, but I want it to continue doing SOS even after the motion goes away or the temperature comes down.
Right now it simply does SOS 1 time and stops.
(sorry if coding is messy)
   int counter;
   int motion = 0;

   void setup()
  {

    {Serial.begin(9600);
     pinMode(4, INPUT);
     pinMode(0, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(1, INPUT);
     digitalWrite(0, HIGH);

     }
  }

    void loop()
   {

   int sensorA0Value = analogRead(A0);
   float voltage = sensorA0Value * (5.00 / 1023.00);
   Serial.print("Voltage: ");
   Serial.print(voltage);

   float temp = (voltage -.5)*100;
   Serial.print("| Temp: ");
   Serial.print(temp);
   Serial.println(" Celcius|");

   motion = digitalRead(4);

   if(motion == HIGH)
    {Serial.println("Motion Detected");}
   if(motion == LOW)
     {Serial.println("No Motion");}

   if(motion == HIGH && temp > 30)
     {
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);

     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);

     delay(600);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(1000);

   }
     else {
     digitalWrite(2, LOW);

     }
   delay(1000);
    }

You could use a while-loop like this:
if(motion == HIGH && temp > 20) {
  while(true){
   SosMethod();
   }
}

to clean everything up, then outside your void loop() you declare your SOSMethod()
void loop() {
 ... .
 }

 void SosMethod(){
 your-led-code-with-delays
 }

It seems this is your SOS code:
if(motion == HIGH && temp > 30)
{
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);

 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);

 delay(600);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(1000);
}

Step 1: I think you want to send the first S (.-.-.-.-) as 3 sequences instead of 2 sequence, so the code is:
if(motion == HIGH && temp > 30)
{
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);

 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);

 delay(600);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(1000);
}

Step 2: Reduce the duplicate code (each 6 sequences of digitalWrite and delay), you will get:
if(motion == HIGH && temp > 30)
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

void send(int delayTime)
{
   for (length = 0; length < 3; length++)
   {
      digitalWrite(2, HIGH);
      delay(delayTime);
      digitalWrite(2, LOW);
      delay(600);
   }
}

Than you want to fix your problem to keep it sending
Instead of
if(motion == HIGH && temp > 30)
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

Use
while ((motion == HIGH) && (temp > 30))
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

For easy reading, I always use parenthesis around equal conditional operator (like ==, >).
The variables motion and temp will not be changed in the while loop, so you can use a while here. It is assumed that the variables are not changed in an interrupt.

In this instance, while (condition) is indeed equivalent to if (condition) while (true). The later, however, clearly exposes the intent of the programmer, whereas the former is very likely to cause confusion.

This may be unrelated to the actual question but... your Morse timings
are completely messed up. The standard timings are:
element         duration
------------------------
dot                 1
dash                3
interelement gap    1
intercharacter gap  3
interword gap       7

where the time unit is the duration of a dot. A correctly timed SOS can
be implemented as follows:
const uint32_t DOT_TIME = 150;  // 8 words per minute

void dot() {
    digitalWrite(2, HIGH);
    delay(1 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void dash() {
    digitalWrite(2, HIGH);
    delay(3 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void send_sos() {
    dot(); dot(); dot();
    dash(); dash(); dash();
    dot(); dot(); dot();
    delay(6 * DOT_TIME);  // interword gap
}

Notice that there are no intercharacter gaps within SOS, as this is a
procedural signal, transmitted with no letter boundaries. It
is not a three-letter word. The last delay is written as
6 * DOT_TIME as there is already a one DOT_TIME delay at the end of
the function dot().


text:
how to use arduino to detect an 8Mhz ultrasonic pulse using piezo disc as receiver?
i need a code to detect an 8MHz ultrasonic pulse and show its properties eg wave pattern and amplitude on serial plotter( like an oscilloscope)

Which Arduino do you think you want to use for this?

I have arduino uno...do you think it'll work?

In a word: no.
Let's crunch some numbers...  You want detail like an oscilloscope.  Okay...
My scope is 50MHz bandwidth and runs at 1 giga samples per second.
Drop that down to 8MHz with the same kind of resolution, and you get (1,000,000,000 * (8/50)) = 160,000,000 samples per second.
That's 10 times more samples per second that the clock speed of the Arduino, and it takes at least 1664 clock cycles to take one sample.
So, no.  You need a board with an ADC which can run in the hundreds of millions of samples per second. The Arduino can only run at just under 10 thousand samples per second.
A slight discrepancy.
Even the Arduino Due can only get as good as 1Msps. I have seen MCUs with 15Msps theoretical maximum, but for the kind of output you want you would need considerably more.
So no, there won't be a cheap development "Arduino-like" board around that will do what you want. There may be an expensive one with a very fast CPU, DSP, ultra-high-speed ADC, etc, but you won't be programming it with Arduino, and you most likely won't be able to afford it to just play with.

Thanks for the info but what is the highest value of frequency that arduino can detect with its clock speed of 16Mhz?

You can sample at a maximum of 9615 samples per second, so 4807.5Hz is the maximum frequency component you can recover.  If you don't care about the shape of the signal you can turn it into a square wave and use digital inputs (such as the T1 input to Timer1) to measure the frequency, but that's all you'll get - the fundamental frequency. No shape, no amplitude, nothing - just the fundamental frequency. And 8MHz is the absolute top limit (F_OSC/2).


text:
I can send on software serial, but not read?
I've been cracking my head over this for a long while.
Like many before me, I'm trying to send and receive data from a HM-10 bluetooth module, arduino mega adk and the app called BLE Scanner. I've figured out receiving alright. Whatever I write into the serial monitor, shows up on the app. Whatever I write into the software serial, shows up. However, I haven't figured out how to read from the software serial. The available function never gets triggered, and always printing out the software serial read is always -1

The app supports sending data over bluetooth as well. However, using:
    #include <SoftwareSerial.h>
SoftwareSerial blueSerial(14, 15); //RX, TX
  blueSerial.begin(9600);
  Serial.begin(9600);
while (1)
  {
    blueSerial.listen();
    if (Serial.available()) {
      Serial.println("Writing");
      blueSerial.write(Serial.read());
      Serial.println(Serial.read());
      Serial.println(blueSerial.available());
    }
    if (blueSerial.available()) {
      Serial.println("Blueserial writing");
      Serial.write(blueSerial.read());
    }
}

The listen function is used out of pure desperation.
How do I fix this? This should be working right? Since I want to be sending AT commands to the bluetooth modules at some time and read their output, getting this to work is really important.

Have you tested the HM10 using a usb to serial adapter?

What do you mean? The Arduino is connected to the laptop, and I'm reading of Arduino IDE's Serial Monitor. I don't have any special cables but the one it came with(the one that puts the code in the board)

what is while(1)? let the loop() loop

Why on earth are you using software serial????

How do you take this tone and not suggest an alternative? @Majenko

Because I'm royally fed up with seeing people do it. I would love to know why they do it.

What do you expect me to give you right here? Mathematical analysis on why hardware serial didn't work on my literal first project in arduino but software at least nudged my progress a bit? I don't know, one worked a bit, one didn't work at all.

If hardware serial isn't working then you are doing something fundamentally wrong.

If hardware serial doesn't work, then you have a problem with either your hardware or your code. When you have a problem, the right approach is to troubleshoot it: find out what is wrong and fix it. You can ask for help here if needed. If you just give up and switch to software serial, then instead of fixing the initial problem you are just creating another problem.

Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.
And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.

On Mega you don't need to use SoftwareSerial. Mega has 4 Serials. Connect the module to RX3/TX3 like on the Fritzing in your question and use Serial3 in sketch.
void setup() {
  Serial.begin(9600);
  Serial3.begin(8600);
}

void loop() {

  while (Serial.available()) {
    Serial3.write(Serial.read());
  }
  while (Serial3.available()) {
    Serial.write(Serial3.read());
  }
}

I have to confirm, that what worked on UNO over SoftwareSerial was not working on Mega ... but switch to Serial2 instead worked.

@Uli, on Mega not all pins support SoftwareSerial

If SoftwareSerial is not working then simply do not use it.
You shouldn't be using it anyway.
You have a Mega with 4 UARTs. You are using a pair of the UART pins, and yet you are using SoftwareSerial.
Don't.
instead use the SerialX object (where X is the number by the TX and RX for the pins) to communicate.
SoftwareSerial is only for those times when you don't have enough hardware UARTs, and you have plenty.

Serial3 didn't work in either direction which is why I switched to software serial in the first place

@Juraj I rewired the whole thing a bunch of times, it's now on Serial with TX->1 and RX->0 . Same issue throughout.


text:
The servo sweep library code - "delay" versus "in steps of"
This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.
For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?
Thanks for your time!

when it comes to programming microcontrollers, the microcontroller does exactly what you tell it to do, no more, no less .... regarding servo moves from zero to 60 degrees twice in one second, you can only move zero to 60 once ..... you have to return to zero before the action can be repeated .... the microcontroller  will not return the servo to zero without a specific instruction to do so

as long as it does what I need it to .... you have not clearly defined how the servo should move, so the question is not answerable

Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:
Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).
In order to perform four 60° movements in one second you should wait roughly 4ms between calls.
In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.
Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.

Servo send out command pulse about 50 Hz. that mean no point to update servo position more frequent than that.
Servo.write() give resolution of 1 degree. if you need more resolution you can use servo.writeMicroseconds()
For my approach I calculate position trajectory as function of time and update servo position in while loop using millis() as time base.
Anyway I finish it and implement to library called accServo
https://github.com/Menginventor/accServo


text:
Need some help in coding a "timer" in an if else statement
I want to code something like a "timer" (don't know what to call it) in an if else statement in my arduino uno.
Basically I have 2 buttons. If the button1 is pressed and button2 is also pressed in a certain amount of time (let's say 3 seconds), the code will execute. If button1 is pressed but button2 is not pressed within 3 seconds then it will loop back up. How do I go about writing this code?
I've included a flowchart to make my question clearer.
Thanks all :)
if(digitalRead(button1) == LOW)       // this is where I need help
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=30; x++)
    {
      digitalWrite(dir, HIGH);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 50)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 50)
      {
      }
    }
    x=0;
  }
}

else if(digitalRead(button2) == LOW)    //same here >_<
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=10; x++)
    {
      digitalWrite(dir, LOW);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 150)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 150)
      {
      }
    }
    x=0;
  }
}

}

Hi, I've edited my post. Hope you can help. :)

Your flowchart seems to be in conflict with the code.
button1 and button2 are self-explainatory, but what is the selectButton?
Here's some code which may accomplish what you're trying to do:
uint8_t bool_waitforbutton2 = 0;
uint32_t num_timeatbutton1 = 0;
void loop() {
  //your other looping code here
  if(digitalRead(button1) == LOW) {
    num_timeatbutton1 = millis();
    bool_waitforbutton2 = 1;
  }
  if(bool_waitforbutton2 == 1 && digitalRead(button2) == LOW){
    bool_waitforbutton2 = 0;
    //Your code here
  }
  if (millis() > (num_timeatbutton1 + 3000)) {
    bool_waitforbutton2 = 0;
  }
}

This would give you 3000 ms to press button2 after you've let go of button1 to execute your code, otherwise the "readyness-flag" bool_waitforbutton2 is reset.

sorry for not clarifying, button1 is for choosing the first function, and selectbutton is for confirming to run function 1. Likewise for button2, it is to select function 2, and selectbutton is to confirm.

A flowchart is not bad, but it's not really the most appropriate kind of
diagram for this sort of problems. You should try to think in terms of
finite state machines instead, which is a very useful concept
whenever you try to implement “reactive” systems, i.e. systems that have
to react to some kind of input.
Here is your problem, as I understand it, translated into a state
diagram:

This system has two states:

“waiting”, when it waits for the first button to be pressed
“stand by” when the first button has been pressed and it waits for the
second.

Pressing button 1 makes a transition from “waiting” to “stand by”. The
transition back to the initial “waiting” state can be triggered by two
distinct events:

3 seconds spent in the “stand by” state
the user pressing button 2.

Note that in the second case, the system runs your code while making the
transition.
Once you have the state diagram, and assuming you have read (and
understood) the finite state machine tutorial I linked to, translating
the diagram into code is almost trivial.


text:
How to solve this "xpected primary-expression before ',' token"
I'm new in this arduino world, and I'm having some trouble. I am programming something for a school assignment. The program gives an error, and my teacher also doesn't know how to solve it. Maybe someone can help me?
#include <CapacitiveSensor.h>
#define speaker

CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);

int s1;
int s2;
int s3;
int s4;
int s5;
int s6;
int s7;
int s8;

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

void loop()
{

  s1 =  cs_2_3.capacitiveSensor(3000);
  s2 =  cs_2_4.capacitiveSensor(3000);
  s3 =  cs_2_5.capacitiveSensor(3000);
  s4 =  cs_2_6.capacitiveSensor(3000);
  s5 =  cs_2_7.capacitiveSensor(3000);
  s6 =  cs_2_8.capacitiveSensor(3000);
  s7 =  cs_2_9.capacitiveSensor(3000);
  s8 =  cs_2_10.capacitiveSensor(3000);

  Serial.print("s1: ");
  Serial.println(s1);
  Serial.print("s2: ");
  Serial.println(s2);
  Serial.print("s3: ");
  Serial.println(s3);
  Serial.print("s4: ");
  Serial.println(s4);
  Serial.print("s5: ");
  Serial.println(s5);
  Serial.print("s6: ");
  Serial.println(s6);
  Serial.print("s7: ");
  Serial.println(s7);
  Serial.print("s8: ");
  Serial.println(s8);

  if (s1 > 500){
    tone(speaker,131);
   }
  else if (s2 > 500){
    tone(speaker,147);
   }
  else if (s3 > 500){
    tone(speaker,165);
   }
  else if (s4 > 500){
    tone(speaker,175);
   }
  else if (s5 > 500){
    tone(speaker,196);
   }
  else if (s6 > 500){
    tone(speaker,220);
   }
  else if (s7 > 500){
    tone(speaker,247);
   }
  else if (s8 > 500){
    tone(speaker,262);
   }

  if (s1<=500  &&  s2<=500  &&  s3<=500 && s4<=500  &&  s5<=500  &&  s6<=500 &&  s7<=500 &&  s8<=500){
    noTone(speaker);
  }
}

Tell the line where the error is given.

This is unrelated to your question but the else if construct does not look very elegant, especially if tone s1 is supposed to have an equal priority to say s8.  Can you find another way of doing this part of the code?

Hint: What does "tone(speaker,131); " become if "#define speaker"?

This is the line where the error is given: else if (s8 > 500){
tone(speaker,262);

This:
#define speaker

defines "speaker" as nothing, an empty string. Then:
tone(speaker,131);

is translated into
tone(,131);

which makes no sense. The compiler expected to find an expression before the comma.


text:
Controlling stepper motor direction with push buttons
I'm trying to control the direction of three 28byj-48 stepper motors using the ULN2003 drivers. I am using 6 push buttons, 2 for each motor. what I want is for each motor to be stationary by default and rotate forward when I press on one button and reverse when I press the other.
You can find my code below. When I use the same approach for coding for one motor, it works fine with a suitable speed. But once I add all 3 motors, motor A and C perform fine but with low speed, motor B keeps rotating forward from the start, stops while I'm pushing its forward button and nothing happens when I push its reverse button. I have checked my circuit several times and there's nothing wrong with it.
#include <Stepper.h> //including stepper motor library

//defining pins section

// pins for motor A:
int stepAIN1Pin = 5;
int stepAIN2Pin = 4;
int stepAIN3Pin = 3;
int stepAIN4Pin = 2;

// pins for motor B:
int stepBIN1Pin = 9;
int stepBIN2Pin = 8;
int stepBIN3Pin = 7;
int stepBIN4Pin = 6;

// pins for motor C:
int stepCIN1Pin = 13;
int stepCIN2Pin = 12;
int stepCIN3Pin = 11;
int stepCIN4Pin = 10;

int stepsPerRevolution = 2048; // amount of steps per revolution for the 28BYJ48 motor

int buttonA1Pin = A5;  // pushbutton 1 pin for clockwise rotation of motor A
int buttonA2Pin = A4;  // pushbutton 2 pin for counter clockwise rotation of motor A

int buttonB1Pin = A3;  // pushbutton 1 pin for clockwise rotation of motor B
int buttonB2Pin = A2;  // pushbutton 2 pin for counter clockwise rotation of motor B

int buttonC1Pin = A1;  // pushbutton 1 pin for clockwise rotation of motor C
int buttonC2Pin = A0;  // pushbutton 2 pin for counter clockwise rotation of motor C

Stepper myStepperA(stepsPerRevolution, stepAIN1Pin, stepAIN3Pin, stepAIN2Pin, stepAIN4Pin); // stepping sequence for motor A

Stepper myStepperB(stepsPerRevolution, stepBIN1Pin, stepBIN3Pin, stepBIN2Pin, stepBIN4Pin); // stepping sequence for motor B

Stepper myStepperC(stepsPerRevolution, stepCIN1Pin, stepCIN3Pin, stepCIN2Pin, stepCIN4Pin); // stepping sequence for motor C

void setup()
{
  // Setting up the pushbutton pins to be an input:
  pinMode(buttonA1Pin, INPUT);
  pinMode(buttonA2Pin, INPUT);

  pinMode(buttonB1Pin, INPUT);
  pinMode(buttonB2Pin, INPUT);

  pinMode(buttonC1Pin, INPUT);
  pinMode(buttonC2Pin, INPUT);

myStepperA.setSpeed(15); // Setting the speed for motor A

myStepperB.setSpeed(15); // Setting the speed for motor B

myStepperC.setSpeed(15); // Setting the speed for motor C
}

void loop()
{

int buttonA1State, buttonA2State, buttonB1State, buttonB2State, buttonC1State, buttonC2State;

  buttonA1State = analogRead(buttonA1Pin);
  buttonA2State = analogRead(buttonA2Pin);

 if ((buttonA1State != 0) && !(buttonA2State != 0))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(stepsPerRevolution/8);

 if (((buttonA2State != 0) && !(buttonA1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(-stepsPerRevolution/8);

  buttonB1State = analogRead(buttonB1Pin);
  buttonB2State = analogRead(buttonB2Pin);

 if (((buttonB1State != 0) && !(buttonB2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(stepsPerRevolution/8);

 if (((buttonB2State != 0) && !(buttonB1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(-stepsPerRevolution/8);

  buttonC1State = analogRead(buttonC1Pin);
  buttonC2State = analogRead(buttonC2Pin);

 if (((buttonC1State != 0) && !(buttonC2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(stepsPerRevolution/8);

 if (((buttonC2State != 0) && !(buttonC1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(-stepsPerRevolution/8);

  }

Please don't put phrases like "Urgent" into the title. You won't get faster results with this.

@chrisl sorry I'm new here! fixed

As I see in the source code of the stepper library, the step() method is blocking, until the given steps are done. With this it would be difficult to drive more than one stepper at a time. I think the AccelStepper library uses a non-blocking step function.

Also: Why are you doing an analogRead(), but don't use it as an analog value. Depending on how you connected the pins, the returned values may be zero only a few times when they should be zero, due to electric noise. Why don't you use digitalRead()?

@chrisl thanks a lot! it worked properly by changing to digitalRead()

your choice of variable names is confusing .... it is difficult to tell at a glance what each variable does ..... try using something like  button_A_FWD_pin instead of buttonA1Pin  and  button_A_FWD_state instead of buttonA1State

Try using digitalRead() for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for analogRead().
IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.
To debug this, you might want to Serial.println() the values of your button states to your Arduino IDE and observe if their values are like you'd expect.


text:
Trying to use a 7 segment display to count 0/9 with a potentiometer
im trying to switch number on the display using a
    potentiometer, it is just counting from 0/9.
    All help is much appreciated!
int SegmentA = 6;
int SegmentB = 7;
int SegmentC = 8;
int SegmentD = 9;
int SegmentE = 10;
int SegmentF = 11;
int SegmentG = 12;

const int PP = A0;

void setup()
{
  pinMode (SegmentA, OUTPUT);
  pinMode (SegmentB, OUTPUT);
  pinMode (SegmentC, OUTPUT);
  pinMode (SegmentD, OUTPUT);
  pinMode (SegmentE, OUTPUT);
  pinMode (SegmentF, OUTPUT);
  pinMode (SegmentG, OUTPUT);

}

void loop() {

  int POD = analogRead(PP);
  int SM = map(POD, 0, 1023, 0 , 8);
  switch (SM) {

    case 0:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //0
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 1:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //1
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 2:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, LOW);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //2
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 3:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //3
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 4:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //4
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 5:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //5
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 6:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //6
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 7:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //7
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 8:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //8
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

  }

}

I would shorten the delay (1000) to be much less - otherwise you turn the pot, nothing happens, you turn it some and finally something happens but now you've overshot what you wanted, and you overdo it the other way trying to get to where you wanted.  Try a delay of 50 to 100, have it be much more reactive to turning the knob.  You can then move on to using a rotary decoder with detents, one click for one number change.  Here's a poorly lit example with 2 digits and rotary encoder.  In this case, a shift register was used to drive each display (vs multiplexing).

https://www.youtube.com/watch?v=f51eSlcZt-g  The link.

You miss the break statement at the end of each case. e.g.:
  digitalWrite (SegmentF, LOW);
  digitalWrite (SegmentG, HIGH);

  delay(1000);

  break;

case 4:

This causes each case to perform, and continue with the next case. However, since there is a delay of 1 second, it looks like it is counting.
Actually, I would expect it counts from a certain value depending on the pot meter to 7, since there is no digit 9 implemented, and the delay for the 8 digit is missing too.
To further improve your code, you can add the delay not in every case but at the end, since I assume there always will be one digit selected.
Also you can make a function void showDigit with a parameter for each of the possible segment states and replace all (almost) duplicated code by that function call, or send the digit and use showDigit to set internally the states of each segment (by using a boolean array[nr_of_digits][nr_of_segments], somewhat like Nic Hartley proposes below.

I would add that you don't even need that switch -- you can easily have a const bool digits[7 * 10], then pass digits[7 * digit], and in the function pull from param[0], param[1], etc.

@NicHartley Thanks ... I think a two dimensional array is than even better, but the use of an array is better in general.

@Michel Keijzers I couldn't remember the syntax for a 2D array off the top of my head so I just went with 1D, but you're correct -- either would work. 2D would probably be prettier.

Actually, strictly speaking, you could also do a const uint8_t digits[10];, then access the individual segments with digits[n] & (1 << segment), if you wanted it to be the least readable possible code. I wouldn't recommend that over the array (probably 2D array) approach, though, unless you have some extremely tight memory requirements.

@NicHartley since the Arduino has only 2 KB this might be useful, but indeed, only when needed. I always prefer readability over memory reduction.

@MichelKeijzers I suggested it only for the very rare circumstances where you find yourself exhausting all 2KB and need to compact things down even more. It's definitely not a good thing to start with, I agree.

@NicHartley I run out immediately with 2 KB (that's why I want to do my 'main' project with an STM which has 192 KB (but maybe I should have used a Raspberry).

@MichelKeijzers Huh. I've never had an issue with it. I "grew up" in very tightly constrained environments, though, so maybe I have a different style. Anyway, this has all gotten somewhat off-topic, haha.

Let us continue this discussion in chat.

You'll want a single delay (if any) at the bottom of the loop() function. You may not need it since it will keep displaying the current digit until you move the potentiometer. Exception: if the pot is near the edge between 2 digits, you could see some dithering.
Replace the delay-calls in the cases with break; statements. Otherwise whichever case you call will fall through into the case below it, and so on, displaying subsequent each digit in turn, which isn't what you wanted (and is what you are already seeing).
Change the map() call to map(POD, 0, 1024, 0 , 10). Otherwise there will be no '9' band on potentiometer and the '8' band will be only 1 value wide (out of 1023): exactly the value "1023". You'd like the '9' band to be about as wide as all of the others. It's even possible that a given potentiometer won't get close enough to zero resistance for you to get a 1023 reading.


text:
Arduino baud rate 8 times too high?
I'm having a strange issue where in order to get the expected serial output on my serial monitor, I have to set the baud rate on my serial monitor to be 8 times higher than the rate that i set in my Serial.begin(). For example, Serial.begin(4800) works with a serial monitor baud rate of 38400.
The setup is an atmega328P and an atmega8u2 built up on a breadboard similar to an UNO R1. I followed Nick Gammon's tutorial and his scripts to flash the 328P with the bootloader (http://www.gammon.com.au/forum/?id=11637), and I used the DFU programmer (on OS X) to flash the 8u2. When I plug my computer into the USB connector on the breadboard, the device correctly shows up as an Arduino Uno in my computer's devices list using lsusb. I can also flash sketches to the 328P using the breadboard tutorial (https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).
The fact that I get the expected results on my serial monitor (even though it's at the wrong baud rate) leads me to believe my hardware is set up correctly. I'm thinking that it could be a bit/byte confusion in the firmware, has anyone encountered something like this or have ideas? I currently can't flash sketches over the USB connector and I believe it is due to the baud rate mismatch.

Sounds like F_CPU is not the same as the actual frequency of the chip. Check your board configuration and your fuse settings.

The trick though is to find if it's the 8U2 or the 328P that is the wrong speed. You really need a scope or logic analyser for that. Or another USB to UART adaptor that you know can work at the right speed.

There are two baud rates you need to diagnose.  One is the baud rate the ATMega8U2 runs at, and the other is the baud rate the ATMega328P runs at.
You need to work out which one is being calculated wrong:

The ATMega8U2's baud rate is set by the USB connection when you open the port
The ATMega328P's baud rate is set by your sketch

Obviously, the two have to match.  However, a baud rate isn't just set as a number, it's calculated as a fraction of the CPU clock.
If the CPU clock on just one of the chips is different to what the firmware or sketch expects then the calculation for the baud rate will be wrong.
An example:
Your ATMega328P is expected to be running at 1MHz - however, the fuse settings have it set to run from the internal 8MHz clock.  That means everything on that chip will run 8× faster than expected, so you have to compensate with a lower baud rate.
Another example:
Your ATMega8U2 is expected to be running at 16MHz - however, the fuse settings have it set to run at 2MHz.  That means everything on that chip (except the USB which is clocked separately) will run 8× slower than expected, so you have to compensate on the ATMega328P with a lower baud rate.
So check the fuse settings on both chips. Make sure they are set to the right speeds for your firmware and boards.txt file settings.
Also, you should look at getting a cheap oscilloscope or logic analyser. That would allow you to monitor precisely what is going on with the communication between the two chips and work out if the baud rate is actually 8× faster than expected (ATMega8U2 at fault), or the normal speed but you have to specify it as a lower number (ATMega328P at fault).


text:
How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)?
All of the wiring diagrams I've found for wiring up a GY-521 accelerometer to an Arduino have looked something like this:

I've read in several places that it needs to be connected to A4 and A5. I want to connect one to a SparkFun ThingDev, which unfortunately only has a single analog input:

Is this possible?
I only need it for a very simple application (finding out if a machine is vibrating or not).

A4 and A5 on the Arduino double as the I2C pins SDA and SCL.  You are communicating with I2C, not analog.
The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins.  The pinout you show has I2C labeled on pins 2 and 14. While you can use those you could use any two pins of your choosing.
Note that I2C on the ESP8266 has a slightly different begin function:
Wire.begin(2, 14);

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.

default Wire pins in pins_arduino.h for this Thing are 2 and 14. so Wire.begin() is ok


text:
How can I simulate an accelerometer?
I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g.
This means you have a signal averaging at "338" when read using Arduino's analogRead() function, with spikes in either direction when acceleration changes.
You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:
int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  }
  else if (num_random == 0) {
    num_xaxis -= 200;
  }
  else if (num_random < 100) {
    num_xaxis += 1;
  }
  else if (num_random > 155) {
    num_xaxis += 1;
  }
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  }
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;
  }
  Serial.println(num_xaxis);
  delay(10);
}

Explanation: First, the value for 0g is determined from the voltage difference.
A random value is generated, ranging from 0 to 255.
If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added.
If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.
The serial commands only serve to let you watch the result in Arduino IDE's serial plotter.
If you need the spike to occur less frequently, adjust the delay(), or let the counter run to higher numbers.
If the CPU-blocking delay() command is an issue in your project, you could run the randomization code using a timer and an interrupt.
Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155).

An input voltage of 1.65 V (half of 3.3 V) should give you a reading of (1.65 V ÷ 5 V) × 1024 ≈ 338.

You're right of course, I forgot that analogRead() defaults to 10 bit. Thank you, post corrected.