text:
Stacking adc's when making an midi controller ( lots of potmeters)
I'm making a midi controller with the Arduino uno. It contains approximately 50 analog inputs with potentiometers. I have enough MCP3008 adc's here but I have no idea how I connect 2 or more adc's to the Arduino so that I can read 50. How do you stack adc's?

Also asked at: http://forum.arduino.cc/index.php?topic=569402 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

why would you use potentiometers?  ..... digital encoders would make so much more sense

These ADC's use the SPI protocol. Luckily the Arduino has one onboard.
With each ADC you get 8 channels (thus inputs). Since you need more than one SPI device (ADC in your case).
With SPI you can chain multiple SPI devices to your SPI port of the Arduino. To select which is active you use the Chip/Slave select signal. This is a separate GPIO you can define yourself. Read more about SPI to read details.
For 50 inputs you need 50 / 8, rounded up is 7 ADCs. This means also 7 CS pins. Thus in total you need 3 (for SPI) + 7 = 10 pins. I hope you have that many left.
About 'stacking', just put the ADC's on a breadboard and wire them according to the SPI protocol.
See also Arduino Reference SPI

Note that with a large number of devices on a SPI bus like this you may need to reduce the communication speed or include a line driver to overcome the increased capacitance on the bus.

Reduced speed will be built in due to the max clock speed of 3.6 MHz with the MCP3008 - thus SPI clock speed of 2 MHz with a 16 MHz Arduino.

With SPI the SCK, MISO, MOSI are connected in parallel to all devices. The device with the active low Chip Select pin is the one that receives a command and then sends data, the others ignore what is happening.  You can also load data into a shift register to create the chip selects, thus only 4 pins are needed: SCK (13), MISO (12), MOSI (11), to all the devices, and use D10, the SS pin, as the latch pin (SRCK) into a 74HC595 for the 7 chip selects out to the MCP3008s.
The code to loop can be pretty simple.
for (pin = 0; pin <7; pin = pin +1){
  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address] = SPI.transfer(addressByte [address]); // send out address, read in D9, D8
  lowerBits[pin + address] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+1] = SPI.transfer(addressByte [address+1]); // send out address, read in D9, D8
  lowerBits[pin + address+1] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+2] = SPI.transfer(addressByte [address+2]); // send out address, read in D9, D8
  lowerBits[pin + address+2] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+3] = SPI.transfer(addressByte [address+3]); // send out address, read in D9, D8
  lowerBits[pin + address+3] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+4] = SPI.transfer(addressByte [address+4]); // send out address, read in D9, D8
  lowerBits[pin + address+4] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+5] = SPI.transfer(addressByte [address+5]); // send out address, read in D9, D8
  lowerBits[pin + address+5] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+6] = SPI.transfer(addressByte [address+6]); // send out address, read in D9, D8
  lowerBits[pin + address+6] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+7] = SPI.transfer(addressByte [address+7]); // send out address, read in D9, D8
  lowerBits[pin + address+7] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

}

The end result are two 56 byte arrays, upperBits[] and lowerBits[], combine a byte from each for a reading per channel.
I do have a lot of duplicate code there that could likely be reduced to a loop within a loop to remove the redundancy.
'address' could come from an array also, as the data needs to be 0b10000000, 0b10010000, 0b10100000, 0b10110000, 0b11000000, 0b11010000, 0b11100000, 0b11110000
or start with address = 0x80 and add 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70
That code has to integrate to drive the shift register, which I forgot about, so instead of
digitalWrite (csPin[pin], LOW);
and
digitalWrite (csPin[pin], HIGH);

you'd have
digitalWrite (shiftRegisterLatch, LOW); // first MCP3008 CS low
SPI.transfer(0b11111110);
digitalWrite (shiftRegisterLatch, HIGH); //first MCP3008 CS low
// read from ADC0 on first MCP3008 using SPI.transfers above
digitalWrite (shiftRegisterLatch, LOW); // first MCP3008 CS high
SPI.transfer(0b11111111);
digitalWrite (shiftRegisterLatch, HIGH); //first MCP3008 CS high

Repeat for channels ADC1 to ADC7
Then go to the next device:
digitalWrite (shiftRegisterLatch, LOW); // 2nd MCP3008 CS low
SPI.transfer(0b11111101);
digitalWrite (shiftRegisterLatch, HIGH); //2nd MCP3008 CS low
// read from ADC0 on second MCP3008 using SPI.transfers above
digitalWrite (shiftRegisterLatch, LOW); // 2nd MCP3008 CS high
SPI.transfer(0b11111111);
digitalWrite (shiftRegisterLatch, HIGH); //2nd MCP3008 CS high

So the data could be in an array as well: 0b11111110, 0b11111101, 0b11111011, 0b11110111, 0b11101111, 0b11011111, 0b10111111, with 0b11111111 to turn off CS
I'd be using direct port manipulation as well instead of digitalWrite() to speed up latching data into the shift register.


text:
send more than one byte at a time SPI Arduino
I have recently been trying to send integers via SPI between two arduino Uno's. I am using the first example of Nick Gammons tutorial, and trying to modify it to get a basic understanding of how to communicate via SPI.
http://www.gammon.com.au/spi
MASTER
// Written by Nick Gammon
// February 2011

#include <SPI.h>

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{

  char c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Hello, world!\n" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

SLAVE - WITHOUT INTERRUPTS
// Written by Nick Gammon
// February 2011

#include <SPI.h>

char buf [100];
volatile byte pos;
volatile boolean process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = c;

  // example: newline means time to process buffer
  if (c == '\n')
    process_it = true;

}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

SLAVE - WITH INTERRUPTS
// Written by Nick Gammon
// April 2011

// what to do with incoming data
byte command = 0;

// start of transaction, no command yet
void ss_falling ()
{
  command = 0;
}  // end of interrupt service routine (ISR) ss_falling

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // interrupt for SS falling edge
  attachInterrupt (0, ss_falling, FALLING);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
// all done with interrupts
}  // end of loop

ORIGINAL ISSUE - I am able to get this working, so the wiring is correct, however i am unable to get it to send anything other than a string. I can change the string and that works, but i am getting confused with pointers in C. Any code i have tried doesn't compile correctly, or doesn't send at all if it does compile. Could someone give me a clue as to where to start with this. My best effort is below
MASTER
#include <SPI.h>

int x = 10000;
int y = 20000;
int z = 30000;
byte High_x = highByte(x);
byte Low_x = lowByte(x);
byte High_y = highByte(y);
byte Low_y = lowByte(y);
byte High_z = highByte(z);
byte Low_z = lowByte(z);

int X =  word(High_x<<8|Low_x);
int Y =  word(High_y<<8|Low_y);
int Z =  word(High_z<<8|Low_z);

  byte myArray[7];

void setup (void)
{

  Serial.begin(115200);
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

 myArray[0] = High_x;
 myArray[1] = Low_x;
 myArray[2] = High_y;
 myArray[3] = Low_y;
 myArray[4] = High_z;
 myArray[5] = Low_z;
 myArray[6] = 0;

  Serial.println(X);
  Serial.println(Y);
  Serial.println(Z);
  delay(2000);
}

void loop (void)
{

  byte data;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (byte * p =  myArray[0]; data = *p; p++)
    SPI.transfer (data);
    Serial.println("sending data");

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

SLAVE
#include <SPI.h>

byte buf [100];
volatile byte pos;
volatile boolean process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();
Serial.println("End of Setup");
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  Serial.println("Beginning of Interrupt Routine");
byte data = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = data;

  // example: newline means time to process buffer
  if (data == '0')
    process_it = true;
      Serial.println("End of Interrupt Routine");
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
    Serial.println("Beggining of Loop");

  for(int i = 0; i < 100; i++)
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf[i]);
    pos = 0;
    process_it = false;
    }  // end of flag set
    Serial.println("End of Loop");
}  // end of loop

In the future i hope to send 10 16-bit integers over SPI from an arduino to an arduino or maybe arduino to a raspberry Pi.
Thanks
EDIT -I have started using the code that uses interrupts and managed to get the data i need sent across, however, i can only get the correct data by setting both the first and second element of the array to "High_x", otherwise it skips the first part of data?
NEW MASTER
#include <SPI.h>

int x = 10000;
int y = 20000;
int z = 30000;
byte High_x = highByte(x);
byte Low_x = lowByte(x);
byte High_y = highByte(y);
byte Low_y = lowByte(y);
byte High_z = highByte(z);
byte Low_z = lowByte(z);

int X =  word(High_x<<8|Low_x);
int Y =  word(High_y<<8|Low_y);
int Z =  word(High_z<<8|Low_z);

  byte myArray[8];

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

 myArray[0] = High_x;
 myArray[1] = High_x;
 myArray[2] = Low_x;
 myArray[3] = High_y;
 myArray[4] = Low_y;
 myArray[5] = High_z;
 myArray[6] = Low_z;
 myArray[7] = 0;

  Serial.print("wait for loop");
  //Serial.println(X);
  //Serial.println(Y);
  //Serial.println(Z);
  delay(2000);
}

void loop (void)
{

  byte data;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (byte * p =  &myArray[0]; data = *p; p++){
    SPI.transfer (data);
  }
  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

NEW SLAVE
byte buf [100];
volatile byte pos;
// what to do with incoming data
byte command = 0;

// start of transaction, no command yet
void ss_falling ()
{
  command = 0;
}  // end of interrupt service routine (ISR) ss_falling

void setup (void)
{

  Serial.begin(9600);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // interrupt for SS falling edge
  attachInterrupt (0, ss_falling, FALLING);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte data = SPDR;

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = data;

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  for(int i = 0; i < 100; i++){

    Serial.println (buf[i]);
    pos = 0;
    delay(1000);
  }
}  // end of loop

Any suggestions on why this is necessary? Is there some basic SPI idiosyncrasy I'm missing?
Thanks all
Ross

You have a couple of issues going on here.
First of all, Nick Gammon's example is transmitting strings. Strings have the property that a particular value, '\0' (null), cannot normally appear in the string itself, and it can therefore be used as an "end flag" to mark the end of the string. This is why the for loop on the master side works correctly.
Note that the null itself is NOT transmitted over the SPI link. Instead, Nick shows an example of using another character ('\n' - newline) to trigger processing on the slave side.
If you want to transmit binary data, which could easily contain bytes of 0x00 (null), you need to find a different way to delimit the data on both the sending side and the receiving side. Your example data (16-bit integers of 10000, 20000 and 30000) doesn't contain any null bytes, but you can't rely on that in general. Also, because the null doesn't actually get transmitted, you can't use it on the receiving side to trigger processing.
There are a couple of approaches that are frequently used to send binary data:

Send the number of bytes explicitly at the beginning of the transaction, and trigger receive-side processing once that number of bytes has been received.
Use a "special" value (e.g., null) to mark the end of the data, but then you have to "escape" that value in some way if it ever appears in the actual data.

In addition to all of that, you have a bug on your master side code. The initialization of your for loop, byte * p =  myArray[0] does not set the pointer p to the address of myArray as intended; instead, it sets it to the value of the first byte in the array, which is 0x27 (High_x). You need to say either byte * p =  &myArray[0] or simply byte * p =  myArray.

Thank you for a detailed answer. So first, sending 10 x 16 bit integers (output of mpu9250)  which would you say is the best method? A "\n" isn't going to appear in the output as I would handle that once sent. If not, could you elaborate on "receive side processing" even if just a link please. I will change the for loop and report back. Thank you

If it were me, I would probably use SS to delimit the data explicitly. Nick shows examples of this using either polling or interrupts.

OK, i'm looking at the interrupts now, however his example doesn't seem to collect the data on the slave side? Can you shed any light on a method of accomplishing this? I'm trying not to just use "if(digitalRead(2) = etc){ stop code}

No, he doesn't collect it on the receive side in that example; he just processes it directly in the ISR and sends it out again. But there's no reason you can't put the data into a buffer just like in the earlier slave-side examples.

Well I have transmission! using interrupts and placing the data in a buffer. However out of the 6 bytes sent, the first one is missing, the next 5 are correct, and there's a strange one that matches nothing at the end. posting the code here will go over the character limit, do i put it as an answer to my question? or change the original post?

Edit your question, and replace your code with the latest version. Note that I removed Nick Gammon's name from your code. I doubt that he would want to be associated with code that he didn't write.

Yes i did notice. And especially associated with the dog turd i'm calling code lol!

I can see two big problems at your code (there could be more, but i didnt look that hard).
First is using Serial.println in interrupt routine. This prevent receiving of more than one byte as Serial.println will take much more time to execute than receiving 6 bytes (even on slow SPI clock) on SPI. In most cases Interrupt routines should finish fast.
Next problem is that you are testing for char 0 ('0') which is not equal to byte 0 you are sending as end of data, but has value of 48 in decimal.
Edit for how to test for end of data:
You can test for end of that few different ways, having fixed number of byte transfers, setting interrupt on slave select pin or encode data binary data in base64 and use control char. I would recommend interrupt.

OK, i will refrain from randomly putting in Serial.prints. Seemed the easiest way to visualise what the code was doing and were to be removed when the code worked. I didn't realise it could STOP it working! I now have added and since removed a serial.print in the Master code in the FOR loop to see if the data that was being transferred was correct and it does work. So the problem is receiving? What could i use to test for the end of the transfer? I'm looking into interrupts but is there other, not as elegant tests. just to test if the principle works then tidy afterwards? Thanks

source: Stack Exchange

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

sort: votes


text:
Using WifiUdp.h on Arduino Mega and ESP8266?
I was trying to run this library on Arduino Mega, using ESP8266 as replacement of Wifi Shield, as suggested on my older thread.
The problem is, I got error in compiling, after with this code :
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>

#include "AppleMidi.h"
APPLEMIDI_CREATE_INSTANCE(WiFiUDP, appleMIDI1);
....

exit status 1
'WiFiUDP' was not declared in this scope

if I modified the code into this :
#include <WiFiEsp.h>
#include <WiFiUdp.h>

#include "AppleMidi.h"
APPLEMIDI_CREATE_INSTANCE(WiFiUDP, appleMIDI1);
....

I got this error instead

C:\Program Files
  (x86)\Arduino\libraries\WiFi\src\utility\server_drv.cpp:313:40: error:
  'WARN' was not declared in this scope
WARN("error waitResponse isDataSent");

                                    ^

exit status 1

Full code here at pastebin.
I was pretty much stuck now. Please help! :(
Thanks :D

WiFiUdp.h is part of the WiFi library for the Arduino WiFi Shield. you can't use it

the WiFiEsp class for UDP is WiFiEspUDP
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include "AppleMidi.h"

APPLEMIDI_CREATE_INSTANCE(WiFiEspUDP, AppleMIDI);

So I would just need to change WiFiUDP to WiFiEspUDP and I'm good to go?

yes, the macro creates an object with template type AppleMidi_Class<WiFiEspUDP> AppleMIDI;

gonna test this tonight. if this works, gonna accept it as answer. thanks for helping me once again :D

I used #include "WiFiEsp.h" and #include "WiFiEspUdp.h" instead and it compiled. thanks!

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


text:
Using delay(1000); without influence on analogWrite?
So, I'm trying to read the voltage on analog pin A0 and make a "regulation", where if the voltage will be lower than 2.5V (analog value 512), then it should be output pin 9 used as PWM with duty cycle of 50% ( analogWrite(ledPin, 128); ) unless the voltage rises again higher than 2.5V.
Where/how am I supposed to use mentioned line ( analogWrite(ledPin, 128); in IF sentence, so it will be used continuous untill it is reached the limit?
PS: I just want to refresh LCD with frequency of 1 Hz while PWM works independently of delay(1000). How is that even possible?
How am I able to do that?
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const int numRows = 2;
const int numCols = 16;

void setup() {
  lcd.begin(numCols, numRows);
}

void loop() {

    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
        lcd.setCursor(0, 0);
        lcd.write(voltage);

        delay(1000);
}

you make no progress. you ask always a variation of the same thing. study the BlinkWithoutDelay example

You didn't understood the question.
I'm not asking for finished code, I'm asking for an explanation on how-to.

read this post .... it is one of yours .... https://arduino.stackexchange.com/questions/56061/refreshing-lcd-with-different-frequency-than-output

The PWM started by analogWrite will not be influenced be the delay, because the analogWrite function only sets the registers and starts the PWM. The PWM generator is independent from the CPU on AVR microcontrollers. On esp8266 for example the PWM is generated with use of interrupt and it is too not influenced by the delay function. To stop the PWM you must call analogWrite with 0 or change the pin mode.

You don't need an if-statement here. You can simply contineously take the measurements and act accordingly.
About the delay(1000):
It is considered a bad coding practice to use delay(), especially for longer periods, because it's just busy waiting. In real life you wouldn't just sit fiddling your thumbs, until a task is done. You would do something else in the intermediate time. Here you can reach this by using non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE.
About PWM:
PWM is not handled by the software, but by the hardware. The Atmega on the Arduino has dedicated PWM hardware included in the package, which will handle the control of the PWM pin, so that the CPU can do other things.

Okay, but is there then a line, which WILL refresh the state shown on LCD?
I can't figure out this part of the job.

the OP has posted a question here ...https://arduino.stackexchange.com/questions/56061/refreshing-lcd-with-different-frequency-than-output .... the use of delay() was addressed ..... it appears that the OP is unable to learn from experience

I think you need something like this, with a flag so you are not contantly restarting the PWM on pin 8 and making the output erratic:
void loop(){
if (analogRead(A0)<512  && halfLevel9 == 0){
analogWrite (9, 128);
halfLevel9 = 1; // flag to let you know it's been set
}
else {
analogWrite (9, withWhat?);
halfLevel9 = 0;
}
// use blink without delay to determine if 1 second has passed
{
// write whatever is going to the LCD
}
// do other stuff while the 1 second passes
}


text:
How does one **get** attributes for SD files?
To be able to set the date and time of the files on my SD card I followed this answer: https://arduino.stackexchange.com/a/39127/49678
Now I am wondering How do I read the values out in the microcontroller?
To clearify, I get the correct timestamps when I remove the SD card and view them on a PC, but I also want to be able to read this on the microcontroller.
Inside SdFile.cpp on line 1025 there is a function called timestamp which is used to set the timestamp but I cant seem to find any function to read it.
https://github.com/adafruit/SD/blob/master/utility/SdFile.cpp
I would prefer a solution where I don't have to add it to the library myself.
The underlying problem I am facing is that I want to log files, and once the memory is full I which to remove the oldest files.

There are two libraries. The standard arduino SD library and the SdFat library by Bill Greiman ( https://github.com/adafruit/SD/blob/master/utility/SdFile.cpp ), the rest are copies, sometimes with a few extras. Even the arduino SD library was originally written by Bill Greiman. An example with the callback is here: https://github.com/greiman/SdFat/blob/master/examples/Timestamp/Timestamp.ino An example to print the date is here: https://github.com/greiman/SdFat/blob/master/src/FatLib/FatFilePrint.cpp You could avoid all of this and put the date and time in the filename.

In the FAT filesystem the timestamps and other attributes are stored in the directory, not in the file.  So you need to read the "file" that is the directory that contains the file you're interested in.
That "file" contains entries in a pre-defined structure. Reading each block of data using that structure gives you the information for each file in turn.
You can just do a normal SD.open(...) call to open the directory that contains your file, and then read chunks of data from it to get each file entry.
That data is arranged in the directoryEntry structure (here), so reading a block of data with File.read(...) into a variable of that structure type will yield your data:
struct directoryEntry dirent;

// myDir has already been opened and points at the start of your dir
while (myDir.read((uint8_t *)&dirent, sizeof(struct directoryEntry))) {

    // Names are tricky to print. Also you should check for deleted files here.
    Serial.print("Name: ");
    for (int i = 0; i < 11; i++) {
        Serial.print(dirent.name[i]);
        if (i == 7) {
            Serial.print(".");
        }
    }
    Serial.println();
    Serial.print("Creation Time: ");
    Serial.println(dirent.creationTime);
    Serial.print("Creation Date: ");
    Serial.println(dirent.creationDate);
}

You need to get an SdFile object for your file then use the SdFile::dirEntry method to get the directory entry for the file.
The directory entry (struct directoryEntry) has the timestamps.

Please tell that this is for the SdFat library. The example for dirEntry is the same I gave: https://github.com/greiman/SdFat/blob/master/examples/Timestamp/Timestamp.ino

@Jot, the SD library is the SdFat library wrapped into simplification with Stream implementation. it should be possible to use the SdFat part to get to timestamp

Thank you for your answer, however I am unsure how to do this. How would I go about to get an SdFile object? The only function I can find that returns SdFile in SDClass is:
SdFile SDClass::getParentDir(const char *filepath, int *index)


text:
Battery voltage monitor right after deep sleep
i have my esp32 module in deep sleep and i use it with a couple of buttons using a wake up that detect the button pressed
now i'd like to have a battery level to send to a server right before going back to deep sleep. How can i do it?
and what cheap rgb led do you suggest using?

what cheap rgb led do you suggest using?  ... use for what?

for usage in combination with low power device drived by an esp32

Using "battery level" (voltage)  is poor way to monitor its useful life. Battery discharge  characteristic varies with its technology.
On the other hand many electronics devices are very tolerable as far as "supply level " AKA voltage.
RGB LED light intensity can be made to monitor different voltage, however, I fail to see how you propose to send the LED intensity level /state to other device.
Addendum
As I pointed out - the battery useful life depends on technology.
You mentioned AAA , hence I assume alkaline battery.
Then I would suggest software solution.
Let the server monitor the actual running time of your device.Then measure or calculate the load your device is drawing from the battery.
Then determine or calculate the discharge curve of your battery and let the server "output" the battery life / discharged level in relation to time. Perhaps I misunderstood and you actually wanted the RGB LED to be connected to the server. Then you can display green LED up to 80% of battery life and so on ...Keep in mind that the discharge curve is pretty abrupt at the end of battery useful life,

i need the esp32 to know the battery level, and power source will always be 2 aaa battery, so it can send to a server the estimated battery lifer remaining


text:
IoT gabage monitoring system with my own Android application
I'm developing a device system in our campus - my aim is to provide three IoT smart garbage containers that will get the fill level (to determine the space of garbage inside and to inform the garbage collector if the garbage is empty, not yet full and full), temperature and humidity from the garbage bin and will send the information to my application that I'm going to develop.
I don't know how I can connect these three IoT devices which are a fair distance from each other. I know it should be wireless though I can't figure out the exact Arduino device to provide connection to my mobile application.

Does your campus have WiFi? If so, go with EPS8266 if its pins are OK for your sensors.
ESP Pinout
You'd want to keep an eye on power consumption; you'd sample your sensors per desired interval and deep-sleep at all other times. Check out available sleep here. It also has en example of how to sample and send a sensor, and sleep afterwards.
On the application end, you could either use a ready service such as Blynk, or go for a custom solution and send the data on your server. Of course, you would then need to write an API and some sort of application to present your data.
Let me also point out that for measuring garbage level, you should calculate the total volume of your bin and subtract the volume of garbage your sensor detects. Having non-uniform trash would give you some trouble, but it's a good technique for an estimation of garbage volume. Also, if using ultrasonic distance sensors, given the fact that you have temperature readings available, you should compensate your measurements; check this out.

thank you! :) please guide me for more details. I don't know how to code on ESP8266 and connect it from those 3 devices.

have a look at the second tutorial in the link I provided here. He is presenting a very similar project.

thank you @dBm do I need one breadboard for each sensor devices?

SIR should I use a wifi-module or not?

sir another one should we used a battery for it and battery case holder? thank you


text:
Arduino will not recognise USB ports on my Mac running Sierra
Arduino will not recognise USB ports on my Mac running Sierra
I am a teacher who helps teachers to use LilyPad. I used to be able to plug in my LilyPad Arduino and see the USB port. I have read all the answers and dowloaded the drivers from Spark fun and another driver from Github. Nothing is working and i am not technical enough to find the answer myself.  I have spent three hours today trawling through the answers to this problem and still cannot fix it myself. I am a luddite who needs a simple step by step remedy. Apple support had no idea when I rang them and told me it was an Arduino problem and to talk to them. you cant talk to anyone at Arduino you can only go to the forums. the forums tell you to read others answers before you post. I have. it's still not working. i need help. And not a lecture about being on a forum asking dumb questions.
I even mucked around in terminal and am hoping it's not a 'terminal" problem because I have no clue what i am doing. If you can explain in plain speak please respond. i have to teach this stuff in 4 days.

This is the message I get when I try to upload a sketch

LilyPad USB implements a atmega32u4 with built in USB. it doesn't have any FTDI or CH340 chips. so you don't need to install the mentioned driver files. the driver for this board installs with Arduino IDE itself. if you try to reset the board with onboard switch, the ports should vanish and reappear. try this and let me know what happens.

Tried pressing the reset button and nothing happened except the built in LED stopped flash and then returned as soon as I let the reset button go. Nothing changed in the ports. Thanks for answering. K

interestingly the usb ports appear when i plug in an Arduino uno. but not for lilypad.

I am a teacher who helps teachers to use LilyPad .... you should really call things by their correct names .... Arduino will not recognise USB ports on my Mac should be Arduino IDE will not recognise USB ports on my Mac

I spoke to a very clever friend who has had similar problems. The answer lay in downloading the FTDI helper package not just the driver.  If anyone else is having a similar problem the website is
https://www.ftdichip.com/Drivers/D2XX/MacOSX/D2xxHelper_v2.0.0.pkg
I downloaded it and now my lilypad and USB port is recognised by the Arduino software.
Just in time for Thursday.
Thanks to all who tried to help.
K

I had a problem getting my computer (Mac Pro, OS 1.12.1 Sierra) to recognize my Arduino Leonardo and Micro boards. Tried many different fixes, nothing worked. Finally used a different cable, and both boards worked fine. NB: I didn't suspect a cable problem, since I removed the cable from a working device. Just to make things weirder, the original device I removed the cable from worked just fine when I re-installed the (supposedly defective) cable.

The Lillypad uses the ATMega32U4 chip. This is the same as the Arduino Leonardo and the Arduino Micro, and suffers the same basic issue that they both suffer from.
Basically, the USB connection is driven by the main chip, not by an interface chip as in most other Arduino boards.  This gives you increased flexibility (e.g., using it as a keyboard or a mouse) and decreased cost (less components on the board), but at the additional cost of certain problems that you have to be prepared to resolve.
Because the main chip runs the USB connection that main chip must be working properly for there to even be a USB connection. With other boards that isn't the case - you can remove the main chip completely and the USB interface chip will still work.  So it is perfectly possible to "kill" the board by installing a sketch on it which stops the main chip from functioning. As soon as the main chip stops functioning the USB stops functioning - and if the sketch that is installed never starts working at all then you never see a USB connection.
Sometimes it is possible to get the USB port to appear for a short period (a few seconds) by pressing the reset switch, but you have to time it right (press reset and immediately select the port in the menu, then press upload, and press reset again just before the uploading itself starts).
The sure-fire fix, though, is to erase the entire chip (along with your installed "broken" sketch) and reinstall the bootloader using the IDE's tools.  You'll need either a hardware programmer (the USBASP is dirt cheap and easy to get on eBay) or another Arduino using the ArduinoISP sketch bundled with the IDE.
If you're going to do any serious work or teaching with any microcontroller-based system it's always good to have a hardware programmer available to help recover from problems, no matter what platform you're working with.  Remember: if there's a way to break it, kids will find it. And do it.

This is a brand new out of the box lilypad board with no sketches loaded on it at all. The ports do not appear when I plug in and select "tools".  This is the third one I have opened and there is nothing that works. I have tried bot USB ports. Nothing. So it isn't broken. It just won't work.

Hmm... That is most odd. I'd suspect your USB cable.  You should also check this answer: https://arduino.stackexchange.com/a/46122/4143

i checked it. it is beyond my skill set!. Thanks anyway. Three usb cords too!

try a computer with Linux or Windows

I had the same problem: my MacBook Air registered by Arduino Board in the USB Device Tree but it was not showing up in the Ports list of the Arduino IDE. It was resolved when I changed the Privacy and Security setting for Allow Accessories to Connect. When I changed the setting to "Automatically When Unlocked" the Arduino IDE was able to recognize my board.
Route to setting: Apple Logo on top Right -> System Settings -> Privacy and Security -> (scroll down to Security) Allow Accessories to Connect.


text:
How do I properly receive MIDI with Arduino, with 6n138?
UPDATE : I still can't receive MIDI as of 2019/07/01.
Here goes so far : I'm trying to follow this schematics from instructables, using 6N138. To make it easier, I'm going to copy his schematics.

===================================
I'm using Arduino Mega. I tried to find specific topic about this and can't find any.
The target is actually send and receive MIDI, then replace the whole Arduino Mega to ESP8266 (probably the ESP-01, or Wemos D1), but I'm afraid it is too specific.
Here's the code so far on PasteBin
Here's my work so far.

The diodes were replaced with LED, because I don't have one Original guide here.
But that schematics on that thread also didn't work for some reason.

What is the Mega supposed to do? The ESP8266 can easily handle all of that on its own.

@tttapa I'm using the esp8266 only as the wifi module, mega for the rest

Define "the rest"?

@tttapa mega would receive the power, receive midi connection, send midi back, and doing everything esp8266 is only for wifi shield replacement.

The ESP8266 can easily handle MIDI connections, as well as receiving power. Using an extra microcontroller is just making everything more difficult, and is a waste of time and resources, in my eyes.

@tttapa yeah, but for now it is impossible to modify my thesis documentation. also since esp8266 has no other serial, I can't debug using serial monitor or similar and probably running blindly. that's why I consider mega at the first place. or you have another solution?

The ESP8266 has two serial ports. One of them can only transmit data. This is not a problem for debugging. On top of that, you can change the pins of the first serial port.

@tttapa but I only got the ESP01 module ... damn I should have think about this before. now I'm pretty much stuck :s

Then you should probably use the Mega. If you were to start from scratch, I would recommend a WeMos D1 mini, or similar, they are $3.50 from China, and break out all usable IO pins, and include a USB interface, so you can just plug it into your computer directly to program it, just like a normal Arduino. If you can get one in time, that would be a good solution, but you can start using the Mega for now. Either way, you'll have to program the ESP8266, you can't use AT commands for RTP-MIDI, AFAIK.

@tttapa for now I do have Wemos D1 Uno, which is kinda the same thing. But the problem is I can't change any specs, it must include mega and esp. I do have the esp with AT firmware that is compatible with this firmware. Idk what to do next ...

Please do not edit the question in a way that makes existing answers invalid or incomplete. "How to create 220 Ω from several 1 kΩ's?" and "Can I replace or omit the 1N914 in a MIDI input?" would be separate questions. (hint: 1/1/1/1/(1+1) in parallel; and see MIDI connectors / Diodes) And the diode is reversed.

How to connect 6N138 to Arduino :

Schematics :

Basically the above schematics and installation is already okay, but instead of 1k, I used 10k on 6N138 PIN 7 to GND.
VCC to 470 ohm is on PIN 6, also RX out, connected in series.

Just in case you want to use 6N137 :

Schematics :

Pin 5 of the MIDI DIN connector goes to pin 2 of the 6N137
Pin 4 of the MIDI DIN connector goes via 330 ohm resistor to pin 3 of the 6N137 (so the 6N137 pins and the resistor are connected in series)
You should also have a reverse connection protection diode between pins 2 and 3 of the 6N137 but I like living dangerously and rely on the diode inside the 6N137
Pin 8 and 7 are connected to VCC
Pin 6 is connected to RX
Pin 5 is connected to GND
4.7 kohm pullup resistor between pin 8 and 6 (VCC and signal out)

Adapted from this blog post.

How to test it :

I used Arduino Mega with this code.
I then attached the Arduino Mega to Hairless MIDI, then to loopMIDI.
Then I read the MIDI output using MIDIOX.

I might update it with H11L1 / PC900 later, if I have some time. Also, I'm going to put this thread in Indonesian in my blog later.

Most start at the midi site at playground.arduino.cc.  But there are numerous web sites across the Internet.  It is important to understand that the MIDI interface uses a current loop to send and receive data.  While the Arduino normally uses voltage levels to communicate.  As such, an electronic interface needs to be built or bought to convert between these two types of signals.  Some interface designs are simple and limited.  Others are complex and robust.

Thats a lot of read. I'll try to read them one by one. Thanks!

Use wikipedia as a reference (don't read it all, just what you need).  The playground.arduino.cc site is likely your best source.  The simple design isn't that simple and the complex not all that complex.  I was looking more for examples of simple (direct connections) and better (optically isolated) ways to convert voltage levels to current loops.

@RinaldoJonathan, your question has changed a lot.  On some bread boards the power doesn't connect from one end to the other.  In such a case you need to jumper the power bus together where they don't connect.  Or move the power wires to the side where you are powering your chip.

the other power line isn't used at all.

@RinaldoJonathan, that is not what I meant.  On some bread boards like yours, there are 4 power bus lines.  Two on each side.  Broken in the middle.  I see your bread board has uninterrupted blue and red lines.  So I think your bread board only has 2 power bus lines.  But it would not hurt to move where you supply power to the end of the board closest to where you use power just to check. Take a look at how the lines are painted on this bread board.

There are plenty of MIDI circuits and most of them are quite simple, mostly an optocoupler (6N137 or 6N138, although I had better luck with H11L1), some resistors and that's mostly it. I also added ferrite beads for EMI protection, but this is not absolutely necessary.
To test your circuit, use a lot of data (e.g. by pitchbend/aftertouch), and play notes meanwhile. If you hear stuck notes (meaning the MIDI Note Off command is missed), you know the circuit is not full proof.
Regarding libraries: the FortySeven Effects library is really easy to use. I used it in the beginning before I moved on to STM32 and having to write my own, but this is a good starting point.
For the schematics I based my circuit of can be found at H11L1 optocoupler.
The best way is to read the official MIDI documentation, see page MIDI 1.0 Specification, than search for
Download the Complete MIDI 1.0 Detailed Specification Document (1996)
(Please Register! It's Free!).

Do you have some example schematics? That would help alot. Thanks!

Note that there has been an addendum in 2014: Electrical Specification Update (CA-033)
It adds a specification for 3.3V systems.

@tttapa Thanks for that remark (didn't know about that addendum)

just realized nobody sells 6N137/6N138, H11L1, or everything else I found at arduino.cc that can be used as alternative.

@RinaldoJonathan I buy them from AliExpress, no problems at all.

@RinaldoJonathan 6N138: https://www.aliexpress.com/item/A6N138-6N138-DIP8/32843461925.html?spm=2114.search0204.3.1.3f891715EwEFhK&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=59100523-2f5e-4065-af82-6c1e5b4c5d08-0&algo_pvid=59100523-2f5e-4065-af82-6c1e5b4c5d08&priceBeautifyAB=0

@RinaldoJonathan 6N137: https://www.aliexpress.com/item/10PCS-6N137-DIP8-6N137-DIP-DIP-8-new-and-original-IC/32911564265.html?spm=2114.search0204.3.1.7ea619e7LGtwnu&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=0090b46e-5df5-4ac3-8601-67cdbb571f94-0&algo_pvid=0090b46e-5df5-4ac3-8601-67cdbb571f94&priceBeautifyAB=0

@RinaldoJonathan H11L1M: https://www.aliexpress.com/item/10pcs-lot-H11L1-DIP-6-H11L1M-Schmitt-trigger-output-at-a-high-speed-In-Stock/32892398601.html?spm=2114.search0204.3.1.36257b29TrA9ZE&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=2f5ebd94-33f1-4a10-9c0c-ebcf204e1f14-0&algo_pvid=2f5ebd94-33f1-4a10-9c0c-ebcf204e1f14&priceBeautifyAB=0

@Michel Keijzers bro I can buy them from tokopedia and it'll arrive in 3 days. but nobody sells them locally.

okay somehow I got 6n137, but again stuck with the schematics.

This is for 6n138 https://electronics.stackexchange.com/q/165255/140343

For 6n137 eg https://goo.gl/images/K71nAo

@MichelKeijzers I have bought H11L1. but it still not working :( I bought it because I see you also used that.

I'm still stuck with receiving MIDI. somehow, Arduino read the input high when nothing connected. But when MIDI cable connected, arduino didn't read it.  https://electronics.stackexchange.com/questions/400080/how-do-i-use-h11l1-correctly-to-receive-midi

I had some troubles with 6N137, but not with H11L1's. Make sure you use the correct resistor values (it matters for what I experienced). Also what helped me a lot was to buy a logic analyzer (about 5$), this way you can see the exact timings. If you need to see if the voltage is going up/down quickly enough you need a 'real' oscilloscope, but the H11L1 should be fast enough.

@MichelKeijzers mind checking my question there at Electronics Stackexchange to see what is actually wrong? I was very stuck ...

I use this library with Arduino Uno (where can change bootloader):
https://github.com/TheKikGen/USBMidiKliK
And after the device is recognized from windows how a Midi device, so not need any other program to interface em.
You can use your preferred sequencer program and your arduino interface is recognized how a midi interface.
The sketch is very simple:
    /**********************************************************************************

  KIKGEN MIDI USB
  A MIDI USB RELIABLE INTERFACE
  USB-MIDI simple converter Sketch for Arduino
       USB                           ATMEGA8U2                    ATMEGA 328P
  --------------         ------------------------------         ---------------
  IN Endpoint  o<--------o USBOUT | usbMidiKliK |  RX o<--------o (TX) MIDI IN
  OUT Endpoint o-------->o USBIN  |  firmware   |  TX o-------->o (RX) MIDI OUT

  The RX/TX on the Arduino must no be crossed, as the ATMEGA8U2 is directly connected
  to the RX and TX pins.  When PIN0 (RX) and PIN1 (TX) are configured as INPUT, we
  can talk directly with the ATMEGA8U2 managing the USB, making the Arduino transparent.

************************************************************************************/

void setup() {

  // Make Arduino transparent for serial communications from and to USB

  pinMode(0,INPUT); // Arduino RX - ATMEGA8U2 TX

  pinMode(1,INPUT); // Arduino TX - ATMEGA8U2 RX

}

void loop() {

}

And hardware schema is this:


text:
Burning bootloader
I'm using arduino atmega 328p and currently using on custom PCB
I programmed using the arduino board and take the IC and migrated to my custom PCB
currently the program run well on the arduino board but after i tried to run it in my custom PCB  and i found it didn't worked
im using along with 16000 mhz oscillator with 22n capacitor

as shown this is my schematic for my PCB

this is my trace for my PCB board
so is this problem caused by my schematics or i didn't upload the bootloader?

You have no decoupling capacitors. Your crystal layout is abysmal.

what do you mean by abysmal and decoupling capacitors?

By abysmal I mean: crystal is too far from the chip pins. The capacitors are poorly grounded. The traces are too angular. There is no guard ring or ground pour. If you don't know what decoupling capacitors are then you need to go and learn the basics of digital circuit design.

Did you use 22nF with the crystal?  You need 22pF.  16 MHz  = 16 x 10^6 = 16,000,000 Hz (not hz).  16000mhz is not correct, that's like 16000 x 10^-3 = 16 Hz.  M = Mega = 1 million.  m = milli = 1/1000.  u = micro = 1/1000000.

I like to give folks the benefit of the doubt, and correct when needed.  Must be the engineer/coach in me, and plenty of non-native English/American/engineer interactions.

oh okay i see, it seems I need to use the 22pF rathe than 22nF, get the crystal corrected so it would near to the chips, but what did u mean the capacitor was poorly grounded? is it means i need to make a larger ground traces for the capacitors?

You should use a ground plane, not ground traces. Reduces the impedance.

Here is a good design. The final posting - right at the bottom.

Schematic corrections:
Missing 0.1uF caps on VCC, AREF pins.
AREF pin connected to 5V - don't do that. It will connect internally using the ADC Mux if used.
C1, C6 need to be 22pF as noted earlier.
Xtal and C1, C6 should be right next to the chip as noted, with no traces going under the xtal.
Board should have Gnd plane anywhere there is not a trace.
Use Vias to connect top & bottom Gnd planes.
Do not use traces to connect all the Gnds - have pins connect to the Gnd planes instead.
Add a 1uF or 10uF electrolytic capacitor where power comes into the board, especially if the power leads will be long.

can i have a full schematic drawing include the components as u listed?

Sure,  http://arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf  This has a resonator instead of the crystal and caps, and also shows a voltage regulator.

i currently using atmega 328p ... is this usable for atmega328p instead atmega328?

328p is the standard chip used on Arduino Uno, Nano, Promini. That is what the bootloaded is set up for.  328 has different 'signature bytes' and uses a little more power.

i just looked at my custom board that i just make. i found out that the pin 20 doesnt have any trace connected anywhere. is this can be a problem that causes my arduino didn't work?

Yes! The chip needs power to work. VCC and AVCC both need to connect to 5V, both should have a 0.1uF cap connected to them also.


text:
Can't write to serial immediately from PC to Arduino nano via pl2303 usb to ttl converter
Goal:
I am trying to send some characters to Arduino through serial from PC via a Prolific PL2303 USB to TTL converter(Chinese clone).
I have wrote a simple sketch(attached bellow) which should light up the LED if 'n' is found or should switch the LED off if 'f' is found from serial.
What's Happening:
I opened up the serial monitor. Send a character(say 'n' which should light up the LED). But nothing happened though the RX/TX LEDs flashed. Then I re opened the serial monitor. And just after re opening the serial monitor LED light up! Every time when I issue a character from serial monitor nothing happens. But just after re opening the monitor character is sent.
H/W Connection:

Arduino Vin -> LiPo positive rail(+11V)
Arduino GND -> LiPo negative rail(GND)
Prolific GND -> Arduino GND
Prolific RX -> Arduino TX
Prolific TX -> Arduino RX

Arduino Sketch:
int led = 13;

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

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    char bytesReceived = Serial.read();
    Serial.println(bytesReceived);

    if(bytesReceived == 'n'){
      digitalWrite(led, HIGH);
    }
    else if(bytesReceived == 'f'){
      digitalWrite(led, LOW);
    }
  }
}

Additional Notes:

Platform Windows 10
Installed Prolific PL2303 driver from here
This code is working using USB cable provided with Arduino.(I need longer cable)

Can't understand why this strange thing is happening. Any kind of help will be appreciated.
Thanks!

When I run the script first time .... what does that mean? .... please describe in detail the steps that you follow to run the script "the first time"

why are you using a python script during testing? .... open a serial monitor window and press keys on a keyboard

That means I have to run the script twice to make the serial transmit to happen:
$ python testscript.py
$ python testscript.py

Also tested with arduino serial monitor. Showing same behavior. If I open serial monitor and send 'n' nothing happens(LED should light up). But after re opening the serial monitor LED lights up(Character is sent).
Actually I am doing a pyqt project with this hence testing with python script.
@jsotola

This sounds like a problem with the Prolific clone.  I know Prolific have been fighting clones of their chips with tweaks to their drivers, so it may be that your Prolific chip is not a real one and won't work right. Try a different adaptor, like an FT232 one, or bend an Arduino without the main MCU (or the main MCU held in RESET) to the use for testing.

I have experienced similar behavior with clone chips. What worked for me is using ferrite choked USB cables similar to these; as you referenced as well, I observed that the problem occurs with either longer cable, or with cables without ferrite chokes on them. This might have to do with the PCB or the cheap chips being prone to electromagnetic interference.

I have purchased a 5m USB extension cable. It's working fine.


text:
ESP8266EX along with Arduino Due rev3 to check wifi status
Hi i am using ESP8266EX along with Arduino Due rev3 to check wifi status. when i compile my following sketch compiler give me error
User\Awais\Document\Arduino\liberaries\espsoftserialmaster\softserial.cpp:27:18: fatal error: gpio.h: no file or directory found
any one help me solve this problem
    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial (15,14); //RX|TX

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

  Serial.begin(115200);
  ESPserial.begin(115200);
  Serial.println("NL & CR");
}

  void loop() {
 // put your main code here, to run repeatedly:

  if (ESPserial.available()){
   Serial.write(ESPserial.read());
  }

if (Serial.available()){
ESPserial.write(Serial.read());
}
  }

And where did you get that SoftwareSerial library? SoftwareSerial libraries are architecture dependent. You can't use AVR ore esp8266 SoftwareSerial library with ARM.
Due has no need for SoftwareSerial, it has 4 Serial ports configured.


text:
Simplify if then else statements for Neopixel/compass project
I am working on a project where a rotary encoder is generating 0 - 359° output and I am feeding that to a 60 Neopixel ring but I need a way to simplify or come up with a better way of a bunch of if-then-else statements.  Here is some sample code.
// NeoPixel Display
  if ((counter >=3) && (counter <=9))
(
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
)
else if strip.setPixelColor(0, 0, 0, 0);
        strip.show();

  if ((counter >=10) && (counter <=15))
(
  strip.setPixelColor(1, 255, 0, 0); //set pixel number 2 and set color to red
  strip.show(); //send color to pixel 2 on NeoPixel Ring
)
else if strip.setPixelColor(1, 0, 0, 0);
        strip.show();

  if ((counter >=16) && (counter <=21))
(
  strip.setPixelColor(2, 255, 0, 0); //set pixel number 3 and set color to red
  strip.show(); //send color to pixel 3 on NeoPixel Ring
)
else if strip.setPixelColor(2, 0, 0, 0);
        strip.show();

You don't use the correct syntax. I assume you mean:
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
}
else
{
  strip.setPixelColor(0, 0, 0, 0)
  strip.show();
}

And similar for the other colors.
First you see there are a lot of occurences of calls to setPixelColor and show. We make a function of this, where the color and the red value is parameterized:
void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
}

Now we can write your code as
// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  setPixel(0, 255);
}
else
{
  setPixel(0, 0);
}

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

And similar for the other colors.
Now we get rid of the if statements. For the first color this will become:
// NeoPixel Display
setPixel(0, ((counter >= 3) && (counter <= 9)) ? 255 : 0);

Combined with the other colors we get
// NeoPixel Display
setPixel(0, ((counter >=  3) && (counter <=  9)) ? 255 : 0);
setPixel(1, ((counter >= 10) && (counter <= 15)) ? 255 : 0);
setPixel(2, ((counter >= 16) && (counter <= 21)) ? 255 : 0);

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

However, the conditions can be simplified by adding them into the function. So we get
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
     ((counter >= lowValue) && (counter <= highValue)) ? 255 : 0,
     0, 0);
  strip.show();
}

If you need to have more checks if a value is in range you can make it a specific function. This will increase the code, but makes it easier to reuse code. So you will get:
// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
    inRange(counter, lowValue, highValue) ? 255 : 0,
     0, 0);
  strip.show();
}

int inRange(int counter, int lowValue, int highValue)
{
   return ((counter >= lowValue) && (counter <= highValue));
}

Thanks for the great help, I learned a lot on this.  Now onto the Roary Encoder that will feed the NeoPixel ring.

Good luck with the project, glad to heard you learnt something (I still do daily too here).

I'd vote this answer up twice if I could! Good job! Loving the use of the ternary operator and the iterative approach to building up the program.


text:
Uno to Mega and where is the error for the interrupt that isn't delared?
I want to read a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R).
A couple questions, I found out that an Uno can only handle 2 interrupt pins and I think I need 3 for the Index.  What do I need to do to the following code to get it to run on a Mega which I believe can handle 3 interrupt pins?
Also I am getting a 'outAChange' was not declared in this scope.
What am I missing here.
I will be using the data from the encoder value to run a NeoPixel 60 for a directional mast/antenna.
Here is the code I am trying to use:
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup(){  // set encoder pins
pinMode(outA, INPUT_PULLUP);
pinMode(outB, INPUT_PULLUP);
pinMode(outZ, INPUT_PULLUP);  //Index

// attach interrupts to pins
attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);

// initialize serial
Serial.begin(57600);
}

void loop(){

if (encoder_save != encoder)  // only print if new value
encoder_save = encoder;

// If Index(Z) reads low reset encoder to 0
if (digitalRead(outZ) == LOW)
{
  encoder = 0;
}
}

{
Serial.println((encoder * 360)/360);
}
}

// interrupt routines
void outAChange(){
// when outA changes, outA==outB means negative direction
encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;
if (encoder < 0)
{
  encoder = (encoder + 360);
}
}

void outBChange(){
// when outB changes, outA==outB means positive direction
encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;
if (encoder >= 360)
{
  encoder = (encoder - 360);
}
}

Your brackets are all messed up.  If you pass your code through an autoformatter (such as the one included in the IDE) you end up with this:
// Wiring connections for my encoder:
// Brown : VCC = 5 to 24VDC
// Blue: 0V(Common) = GND
// Shield: GND
// Black: outA = Digital pin 2
// White: outB = Digital pin 3
// Orange: outZ = Digital pin 4 (Index)
// With these outA/outB/outZ connections and the interrupt code below
// clockwise rotation gives positive encoder counts

const int outA = 2;
const int outB = 3;
const int outZ = 4;

volatile long encoder = 0; // declare volatile since modified by interrupt routines
float encoder_save = 0;

void setup() { // set encoder pins
    pinMode(outA, INPUT_PULLUP);
    pinMode(outB, INPUT_PULLUP);
    pinMode(outZ, INPUT_PULLUP);  //Index
// attach interrupts to pins
    attachInterrupt(digitalPinToInterrupt(outA), outAChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outB), outBChange, CHANGE);
    attachInterrupt(digitalPinToInterrupt(outZ), outZChange, CHANGE);
// initialize serial
    Serial.begin(57600);
}

void loop() {
    if (encoder_save != encoder) { // only print if new value
        encoder_save = encoder;
    }

// If Index(Z) reads low reset encoder to 0
    if (digitalRead(outZ) == LOW) {
        encoder = 0;
    }
}

{                                                << WHAT
    Serial.println((encoder * 360) / 360);       << IS
}                                                << THIS
}                                                << CODE?

// interrupt routines
void outAChange() {
// when outA changes, outA==outB means negative direction
    encoder += digitalRead(outA) == digitalRead(outB) ? -1 : 1;

    if (encoder < 0) {
        encoder = (encoder + 360);
    }
}

void outBChange() {
// when outB changes, outA==outB means positive direction
    encoder += digitalRead(outA) == digitalRead(outB) ? 1 : -1;

    if (encoder >= 360) {
        encoder = (encoder - 360);
    }
}

As you can see, after the end of your loop() function, you have an extraneous block of code with a bunch of random brackets.
You need to decide where in your program that should actually be and move it there, deleting those extra brackets.

I could use a little more help than that.  I am really new at coding.  thanks.

I cannot help you. Only you know where you want that bit of code.


text:
getting SPI SSD1307 to work on Arduino Mega
After some time off, I decided to get back into my project after some help from this topic I started earlier Difference in pinout (types?) Uno/Mega. Unfortunately, even tho I have read multiple times what has been said about the SPI pins on a mega, the displays simply will not work. Both my LED strips and rotary encoder are working, so my code compiles and uploads as it should. The displays are ssd1307 using SPI.
Pinout from MEGA to displays
49 > RST for display1/display2/display3
50 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

Here is the code I am trying to use:
#include <Adafruit_NeoPixel.h>
#include "HCuOLED.h"
#include "SPI.h"

Adafruit_NeoPixel REVLEDS = Adafruit_NeoPixel(7, 2, NEO_GRB);
Adafruit_NeoPixel DASHLEDS = Adafruit_NeoPixel(3, 3, NEO_GRB);

#define SCK 52
#define SDA 51
#define DC 50
#define RST 49

HCuOLED HCuOLED_5(SSD1307, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SSD1307, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SSD1307, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

#define s1 6
#define s2 5
#define key 4

int newCounter = 0;
int oldCounter = 0;
int oldState;
int newState;
int rotated = 0;
int keyState = 0;
int keyReset = 0;

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

  REVLEDS.begin();
  REVLEDS.setBrightness(25);

  DASHLEDS.begin();
  DASHLEDS.setBrightness(25);

  pinMode(s1, INPUT);
  pinMode(s2, INPUT);

  oldState = 1;
  newState = oldState;

  HCuOLED_5.Reset();
  pinMode(53, OUTPUT);
}

void loop() {

  newState = digitalRead(s1);
  if(newState != oldState){
    if(digitalRead(s2)!= oldState){
      newCounter ++;
    } else {
      newCounter --;
    }
    if(newCounter == (oldCounter+2) ||newCounter == (oldCounter-2)){
      if(newCounter > oldCounter) rotateRight();
      else rotateLeft();
      oldCounter = newCounter;
    }
  }
  oldState = newState;

  keyState = digitalRead(key);
  //Serial.println(keyState);
  if(keyState == LOW && keyReset == 0){
    onButtonPress();
    keyReset = 1;
  } else if (keyReset == 1 && keyState == HIGH){
    keyReset = 0;
  }

  for(int i = 0; i < 7; i++){
  REVLEDS.setPixelColor(i, 0,255,0);}
  REVLEDS.show();

  for(int i = 0; i < 3; i++){
  DASHLEDS.setPixelColor(i, 0,0,255);}
  DASHLEDS.show();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
}

void onButtonPress(){
  Serial.println("Pressed button");
}

void rotateLeft(){
  Serial.println("Rotated left");
}

void rotateRight(){
  Serial.println("Rotated right");
}

Now the question is, what am I missing?
TIA!

the SSD1307 supports SPI and I2C. you should provide a link to the display module. SDA and SCK are used to label I2C pins

Sorry forgot to add that this was the SPI version of the ssd1307.

Pin 53 is set to OUPUT as you can see in the code. In the link of my original post you can see that I already had these SPI display work on mu UNO, but not on my MEGA. The display in question are these:
https://nl.aliexpress.com/item/5pcs-7pin-0-96-White-OLED-module-0-96-OLED-New-128X64-OLED-LCD-LED-Display/32650457238.html?spm=a2g0s.9042311.0.0.6d864c4dvMy0SY
I am also planning on adding 2 bigger ones, which are these:
https://nl.aliexpress.com/item/1pcs-Blue-1-3-SPI-Serial-128X64-OLED-LCD-LED-Display-Module-for-Arduino-UNO-R3/32650144885.html?spm=a2g0s.9042311.0.0.6d864c4dvMy0SY

The displays do not use SPI MISO pin. It is 12 in Uno and 50 on Mega. On Mega you try to use pin 50 for DC pin of the displays and it creates a conflict with SPI. MISO should be an INPUT and DC is OUTPUT.

Found the problem... after my break, i forgot that the .refresh() command is actually the command that displays something on the screen, while I kept thinking it was to clear the screen. After adding that to my code together with .clearBuffer(), everything works with the following pinout:
Pinout from MEGA to displays
48 > RST for display1/display2/display3
49 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

With the following code to show different stuff on screen:
#include "HCuOLED.h"
#include "SPI.h"

#define SCK 52
#define SDA 51
#define DC 49
#define RST 48

HCuOLED HCuOLED_5(SH1106, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SH1106, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SH1106, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

int tCounter = 0;

void setup(){
  HCuOLED_5.Reset();
  //pinMode(53, OUTPUT);
}

void loop() {
  //display 3
  HCuOLED_3.SetFont(Terminal_8pt);
  HCuOLED_3.Cursor(44,0);
  HCuOLED_3.Print("Cpt");
  HCuOLED_3.Cursor(20,10);
  HCuOLED_3.Print("Fastlane");
  HCuOLED_3.SetFont(LCDLarge_24pt);
  HCuOLED_3.Cursor(20,30);
  HCuOLED_3.Print("3 - ");
  HCuOLED_3.Cursor(65,30);
  HCuOLED_3.Print(tCounter);
  HCuOLED_3.Refresh();
  HCuOLED_3.ClearBuffer();

  //display 4
  HCuOLED_4.SetFont(Terminal_8pt);
  HCuOLED_4.Cursor(44,0);
  HCuOLED_4.Print("Cpt");
  HCuOLED_4.Cursor(20,10);
  HCuOLED_4.Print("Fastlane");
  HCuOLED_4.SetFont(LCDLarge_24pt);
  HCuOLED_4.Cursor(20,30);
  HCuOLED_4.Print("4 - ");
  HCuOLED_4.Cursor(65,30);
  HCuOLED_4.Print(tCounter);
  HCuOLED_4.Refresh();
  HCuOLED_4.ClearBuffer();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
  HCuOLED_5.SetFont(LCDLarge_24pt);
  HCuOLED_5.Cursor(20,30);
  HCuOLED_5.Print("5 - ");
  HCuOLED_5.Cursor(65,30);
  HCuOLED_5.Print(tCounter);
  HCuOLED_5.Refresh();
  HCuOLED_5.ClearBuffer();

  tCounter++;
}

and the pin 50?

Unused. However It also works if I don't set pin 53 to OUTPUT. Why is this?

SPI library does it in begin

was use of pin 50 as DC one of the reasons why it didn't work?


text:
help with a loop
I recently got into programing and I'm making an alarm. I cant figure out how to make a buzzer loop. I have two blinking LED's and two fading ones. Now I plan to have sound and it won't work.  It only blinks once and stops. I would also like the two fading LED's to fade at different times. I can't figure that out. Here's the code. 8 is the buzzer and red and blue are the fading LED's.
int blue = 6;
int red = 9;
int brightness = 0;
int fadeAmount = 500;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(red, OUTPUT);
     pinMode(blue, OUTPUT);
      pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(8, LOW);
  digitalWrite(8, HIGH);
  delay(10);

 analogWrite(red, brightness);
  analogWrite(blue, brightness);
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 millis();
}

Have a look here, on how you can use different peripherals in a  non-blocking manner. The following code is from the link:
// These variables store the flash pattern
// and the current state of the LED

int ledPin1 =  12;      // the number of the LED pin
int ledState1 = LOW;             // ledState used to set the LED
unsigned long previousMillis1 = 0;        // will store last time LED was updated
long OnTime1 = 250;           // milliseconds of on-time
long OffTime1 = 750;          // milliseconds of off-time

int ledPin2 =  13;      // the number of the LED pin
int ledState2 = LOW;             // ledState used to set the LED
unsigned long previousMillis2 = 0;        // will store last time LED was updated
long OnTime2 = 330;           // milliseconds of on-time
byte brightness = 0;
byte brigthnessInterval = 10;

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState1 == HIGH) && (currentMillis - previousMillis1 >= OnTime1))
  {
    ledState1 = LOW;  // Turn it off
    previousMillis1 = currentMillis;  // Remember the time
    digitalWrite(ledPin1, ledState1);  // Update the actual LED
  }
  else if ((ledState1 == LOW) && (currentMillis - previousMillis1 >= OffTime1))
  {
    ledState1 = HIGH;  // turn it on
    previousMillis1 = currentMillis;   // Remember the time
    digitalWrite(ledPin1, ledState1);     // Update the actual LED
  }

  if(currentMillis - previousMillis2 >= OnTime2)
  {
    previousMillis2 = currentMillis;  // Remember the time
    if (brigthness <= 254) brigthness += brigthnessInterval;
    if (brigthness == 255) brigthness = 0;
    analogWrite(ledPin2, brigthness);
  }
}

Here, two LEDs are controlled with different intervals, I changed LED number 2 to fade in with an interval specified with OnTime2; watch out your fade amount though, because analogWrite has 255 levels, and you immediately increased it to 500. You can add as many intervals as you want in the same manner, and perform tasks in pseudoparallel.

try and analyze this alarm sound sketch
const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

void setup()
{
}

void loop()
{
  alarmSound();
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}

i tried this it sayed alarm sound not declared in scope and i cant figure out how to fix it

you can't compile it in Arduino IDE? what is "alarm sound"? the function is called alarmSound

I suggested the basics in my answer to your previous question - "To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED."
To put that more concretely, instead of brightness, you'll need a redBrightness and a blueBrightness, and initialize them to different values.
   brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}

For instance, initializing them to '0' and '128', respectively, would drive the LEDs 180 degrees out of phase, or one fading up while the other fades down, assuming you use the same fadeAmount variable for both. If you use a redFadeAmount and blueFadeAmount, you can make them fade at different rates, as well.

"I recently got into programing"
So start here :
https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm
To apply such principle start by finding suitable "blink (SINGLE) LED" in Arduino IDE examples. There is no real need to reinvent  the wheel / code when you just starting to learn programming as long as you do not just "cut and paste".
You can blink LED attached to pin 13 without using any additional hardware.
Then find an example doing same without using "delay".
Most newcomers have issues with Arduino hidden main function and navigating "loop".
Once you have hang of the loop function you can add multiple "instances" of blinking LED's, and later consolidate these instances into suitable function.
Then use same approach to your buzzer or any other device.
Good luck.


text:
How do I directly access a memory mapped register of AVR with C
Assume I want to write the following without using DDRD or PORTD:
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
    DDRD = 0xFF;
    PORTD = 0xFF;
}

I found this link which includes a list of mapped registers to memory addresses:
https://github.com/DarkSector/AVR/blob/master/asm/include/m328Pdef.inc
So I replaced one of the keywords with a pointer:
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRD = 0xFF;
    unsigned char *portd = 0x0b;
    *portd = 0xFF;
}

But it's not working (my LED isn't turning on with the second code). Why is that?

It might get optimized out, as it's not volatile. Or it's using wrong instruction to store data so it needs different address.

If you'd use unsigned char *portd = &PORTD; would your pointer work for port manipulation? That would lead to #2. 2. From here:
unsigned char * myportA = (unsigned char *) 0x003B; Of course, adjusted to your microcontroller. If that works for you, I lack of knowledge why would you need to cast it, but if passing the port name by reference works (#1) and direct assign using the hex doesn't, it has something to do with that. 3. Could declaring the pointer variable volatile help, in case something else modifies it?

what in this question is about Arduino?

It's worth exploring how PORTD is defined in the actual AVR header file.  The relevant file is iom328p.h, and it's defined as:
#define PORTD   _SFR_IO8(0x0B)

_SFR_IO8 is defined as
#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)

and
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

This shows that 0x0b is not the address of the PORTD register, but its offset from the address __SFR_OFFSET, which is 0x20.  Indeed, if you look at the ATMEGA328 datasheet, the register summary shows that PORTD is at offset 0x2b.  So that is the address that you would want to access via a pointer.
Note that this also shows the type of the pointer, if we fully expand the original definition of PORTD we get:
#define PORTD   _SFR_IO8(0x0B)
#define PORTD _MMIO_BYTE((0x0B) + __SFR_OFFSET)
#define PORTD _MMIO_BYTE((0x0B) + 0x20)
#define PORTD (*(volatile uint8_t *)(0x2B))

This syntax takes the integer 0x2B, casts it to type pointer to volatile uint8_t, and dereferences that pointer so you can assign to or read from the location the pointer references.  The volatile qualifier is important because it prevents the compiler from optimizing out accesses to memory.  Without it, the compiler may store the value to a register instead, or not store it at all, which would mean your IO port would remain unchanged or appear to report an incorrect value.
To go back to the title of your question, you have asked how to "directly access a memory mapped register in C", well the answer is you do that exactly the way the header file defines for you:
(*(volatile uint8_t *)(0x2B) = 0xFF

aka
PORTD = 0xff

There is no more direct way than this.  The compiler sees a literal address and writes to it.  What you've written is very different (adjusting to use the correct address and type:
volatile uint8_t * portd = 0x2b;
 *portd = 0xFF;

This allocates a location in memory symbolized by portd, which holds the value 0x2B.  When you write *portd = foo, the MCU has to access the location where portd is stored, take the value found there as an address to find the location you actually want to write to.  This method requires that you allocate a place in memory to hold portd and requires an extra memory access to be able to read or write to the port register.  This method is therefore indirect.
In reality, if optimization is enabled, the compiler may optimize the pointer away and replace it with the same literal access as in the PORTD case, however this depends on the program structure, and in particular the qualification and scope of the pointer.  Limiting the scope of portd as much as possible and/or declaring it as volatile uint8_t * const portd = 0x2b (which indicates that the pointer's value is constant even if the value pointed to is volatile) will increase the likelihood of the pointer being optimized away.

The reason the AVR headers define the IO port registers this way is because in addition to the standard load/store instructions that can access the entire data memory address space and take three clock cycles to complete, the IO registers are special, and can also be accessed using IN/OUT instructions, which complete in two cycles.  The load/store instructions use the memory address for the IO registers (starting at offset 0x20), whereas the IN/OUT instructions use the IO address, which starts at 0x00, but corresponds to 0x20 in the memory address space.  From the datasheet:

So when you access an IO location, the optimizer should recognize that it can issue a more efficient instruction than the standard load/store, and it will replace the load/store to 0x2b with an in/out to 0x0b.

Re “ This method requires that you allocate a place in memory to hold portd and requires an extra memory access”: Not really. It compiles to the exact same machine code as PORTD = 0xff.

It may get optimized to the same instructions, but the abstract C machine is instructed to do as I described and there is no guarantee that such optimization will take place.  It will depend on the scope of portd and optimization level, but in any case it's still not more direct than using the existing PORTD macro.

You may then want to make it clearer in your answer that by “the MCU” you mean the abstract C machine, not the actual MCU.

The behavior of the target must be equivalent to the behavior of the abstract machine; that's the whole point.  Accessing a literal address is only equivalent to accessing a dereferenced pointer in a limited subset of cases, therefore the compiler will issue instructions for pointer dereferencing unless it can determine that the literal access is equivalent.  Try different scopes and qualifications for portd and see what instructions are emitted.  In any case, it's worth mentioning the optimization, so I've added that to the answer.

Re “Try different scopes and qualifications for portd”: for the specific case of the question, it will be optimized away. There is no “may”. If you manage to coerce the compiler to store the pointer, I would love to see it, but it will will clearly be a very different code from the one in the question.

See: I have seen many beginners here who are prone to misguided micro-optimization attempts. Some are confused because they severely underestimate the compiler's ability to optimize. Never the contrary. Some avoid using variables for intermediate results under the misconception that they are reducing RAM consumption. Truth is they are only reducing program readability. Your explanations about the purported cost of the portd variable can only reinforce this misconception. Using intermediate variables is one of those cases where one should really trust the compiler to micro-optimize.

You're right, it is almost always best to let the compiler worry about optimizations like this. However, it is important to understand that in the two different cases you are telling the machine to do two different things, even if the syntax looks quite similar.  It's also important to understand how scope and qualification affects compiler behavior.  FWIW, when portd has global scope and is non-const, I still get pointer instructions at any optimization level with AVR-GCC 4.9.2.
Further discussion on this tangent should probably happen in chat.


text:
Arduino sketch not uploading to Arduino Nano
Port is detected and selected but sketch is not uploading to it.
I am getting error:
         avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\ACER\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x2c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

In IDE in the Tools menu, select in submenu Processor the "Atmega 328P (Old Bootloader)" option.
The upload speed 115200 in your console output indicates the you try to upload for new bootloader. The fail to upload could indicate that your Nano has the old bootloader.


text:
My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor
I recently bought this Arduino Fingerprint Sensor FPM10A from Aliexpress. So, when I connected it with my Arduino Nano and uploaded the 'enroll' example and opened the serial monitor. The fingerprint print sensor got detected but when I enter #1 to enroll the fingerprint no output is given on the serial monitor. I think my Arduino Nano just freezes.But other examples such as 'Empty database, it works with no problems. Is this caused by the less powerful Atmega168 microprocessor? If I get a Arduino Uno or an Arduino Nano with an Atmega328P microprocessor will this problem be solved? And I do not think the fingerprint module is defective as other examples worked like a charm.
Please see the attached photo above.

There appears more then one type of FPM10A.  Some with more connections than others.  It would be helpful if you could provide a link to your FPM10A and a data sheet.
Also, an Arduino Nano should use an ATmega328 processor.  If you have a nonstandard Arduino Nano perhaps it would also help to provide links and data sheets to the Arduino Nano you are using.
When using nonstandard Arduinos, it may be best to check for additional processor and / or board support.  And to use (load) them into your IDE when available.

There is no data sheet available

118 bytes for the stack and local variables is not enough. The problem is indeed the Atmega168. The Atmega328P has twice the ram.

Did you buy the arduino board Nano Atmega168 on Aliexpress? Sometimes the cheapest arduino compatible boards are okay, but sometimes they are stripped of decoupling capacitors or the polyfuse is missing (on a uno board). Sometimes they put a Atmega168 on the board, it is a few cents cheaper.
If you buy the cheapest nano compatible board, look at the photo if the quality is reasonable. The newer arduino boards have a ARM Cortex processors. The Atmega328p is still okay for small projects. I suggest to use the Atmega328p as the minimum.
A Arduino nano Atmega328p clone at Aliexpress costs about 2 dollars, so there is no reason to buy an Atmega168.
When the compiler tells you that "Low memory available, stability problems may occur" for the ram, then you can almost be sure that it will not work.
I try to keep about 300 bytes ram available for local variables, stack and the heap. It depends how much memory the libraries require. I also don't use the String objects for the Arduino uno or nano.
For a beginner, you can try to keep at least 500 bytes ram available.


text:
EEPROM size limitation issue
I am creating a test program with Arduino Nano where I can save network and password. Here is my code to start with:
void SaveNetwork(String ssid, String pass){
  String com = ssid + "~" + pass;
  const char *array = com.c_str();
  for(int i = 0; i<sizeof(com); i++){
    EEPROM.write(i, array[i]);
  }
  Serial.println("Saved");
  char ar[255] = "";  //test read string.
  for(int i = 0; i<sizeof(com); i++){
    ar[i] = EEPROM.read(i);
  }
  Serial.println(ar);
}

SaveNetwork("Testing", "Network123......");

Now I print ar string which is suppose to return ssid, "~" and password.
BUT what I get is "Testin" instead of "Testing~Network123......".
Is there is a limitation for EEPROM size? If so, how can I expand the capacity, should I use a memory chip, or what is the code I should use to resolve this?

The problem is with sizeof(com) in your loops. sizeof() is for C arrays, not string objects. If you print it, it will report 6, which is not the length of the array. For string objects you should use com.length() instead. Then the output becomes

Saved
Testing~Network123......

P.S. The EEPROM can store 1024 bytes on ATmega328P-based boards (I believe that's what most Arduino Nanos use (clones included).


text:
Unable to upload sketch using Platformio (but Arduino IDE works)
I am using an Arduino Nano (Clone) which I was programming with the Arduino IDE (Version 1.8.5 on Mac OS X 10.10.5).
Using the Arduino IDE I need to re-plug the Nano before uploading, but after doing this everything works as expected and the sketch is being uploaded successfully.
I then tried to use Platformio core (CLI) and get the well-known not in sync error:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

As said, this error is well-known, esp. in relation to Arduino clones, and reported several times around the Internet with different solutions.
I just wonder how Arduino IDE is able to upload the code successfully, but Platformio is not since both Arduino IDE and Platformio CLI are just calling avrdude to upload the code.
Remark: Uploading the same code to an Arduino Uno works like a charm with both using Arduino IDE and Platformio.

Updates due to further investigation:
I enabled verbose output for both Arduino IDE and Platformio showing the exact avrdude command executed to upload the built hex-file. I adopted the call to avrdude from Arduino IDE with the path of the compiled Platformio code. This works as expected:
avrdude -v -p atmega328p -c arduino -b 57600 -D -P /dev/cu.usbserial-00000000 -U flash:w:.pioenvs/nano/firmware.hex:i

I then had a look at the command used by Platformio which is quite similar but provides an additional -C for a config-file:
avrdude -v -p atmega328p -C /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf -c arduino -b 57600 -D -P "/dev/cu.usbserial-00000000" -U flash:w:.pioenvs/nano/firmware.hex:i

Unfortunately, I am not able to run this command from the Terminal due to an error:
avrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf"
avrdude: syntax error at /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf:1080

try to upload to Nano with Uno selected as board

@Juraj: Using Uno instead of Nano does not work as well.

has Platformio an "old bootloader" option for Nano?

There is a 'normal' and a 'new' option. Both not working. The only difference seems to be the baud rate at first glance. I might have a look at the upload scripts for further differences...

I've tried replicating this issue using a nano clone on mac os 10.12.6 using platformio IDE, and there were no issues. I would try two things: upload a simple blink sketch (or an empty loop) using arduino IDE to make sure the board doesn't try to connect over UART thus interfering with the upload process under platformio; and if this doesn't help, then I would re-flash the bootloader. Also, if platformio is not up to date, it is certainly a good idea to update it to make sure it uses the latest avrdude + config file.

@Im_Int: Updated to Arduino 1.8.7 and tryied to reflash boot-loader. Reflashing did not work with Arduino 1.8.7 but with 1.8.5. After that still not able to upload code using Platformio. Tried another Arduino Nano clone: Was able to upload code once with Platformio, but never again. Uploading with Arduino IDE 1.8.7 works, unable to re-flash bootloader to this board as well. There are several discussions around the Internet about the transfer protocol, the use of reset signal on Reset pin (RST) and a capacitor. So this might me a hardware/board-related issue due to cheap Arduino clones... :/

how do you flash the bootloader?

I used/tried to use an Arduino Uno as ISP since I do not have my original AVR ISP mkII on hand currently

and why did you do that? is it possible that you changed to different bootloader?

I'm having the exact same issue. I'm abandoning platform io because of this. It's rather more difficult than the arduino IDE.

Please use board = nanoatmega328new in your platformio.ini