text:
RFID-RC522 Can't access sector after writing to trailer block
I'm currently using an Arduino Uno R3 and an RFID-RC522 with https://github.com/miguelbalboa/rfid .
I wrote the following bytes to the trailer block in order to experiment with it:
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA };

I wanted to change the default MFRC522::MIFARE_Key key.keyByte so I can read and write to the card using a custom key and leave everything unchanged but I cannot access the sector anymore.
What do I have to do to be able to access the sector again?
Code:
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
/*
 * Pin connections for UNO:
 * 9  - RST
 * 10 - SDA
 * 11 - MOSI
 * 12 - MISO
 * 13 - SCK
 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key; // will hold card info

// Every 4th block is a trailer block that contains access and security info, modulo 4.
const int blockSize = 16;

int writeBlockNumber = 2; // The block we want to write the data.
int readBlockNumber = 2;
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA }; // 16 character max
byte readBlockContent[18] = { 0 };

// Will write the data to the block.
int writeBlock(int block, byte data[]) {
  int status;

  if ( (block + 1) % 4 == 0) {
    Serial.println("Warning: Writing on a trailer block!");
    return 0;
  }

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Write(block, data, blockSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }
  return MFRC522::STATUS_OK;
}

// Will try to dump the whole card info.
void dumpCard() {
  for(int i = 0; i < blockSize; ++i) {
      Serial.print("Block ");
      Serial.print(i);
      Serial.print(" ");
      if ( readBlock(i, readBlockContent) == MFRC522::STATUS_OK ) {
        printReadBlock();
      }
  }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

// Will read the block.
// These functions must be called if you wish to read a new card.
//    mfrc522.PICC_HaltA();
//    mfrc522.PCD_StopCrypto1();
int readBlock(int block, byte data[]) {
  int status;
  byte readSize = blockSize + 2;

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);

  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Read(block, data, &readSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  return MFRC522::STATUS_OK;
}

// Will print the contents of the readBlockContent.
void printReadBlock() {
  for (int i = 0; i < blockSize; ++i) {
    Serial.print(readBlockContent[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" -> ");
  for (int i = 0; i < blockSize; ++i) {
    Serial.write(readBlockContent[i]);
  }

  Serial.println();
}

// Will print the card id that is stored in mfrc522.uid.uidByte
void printCardUid() {
  Serial.print("Card ID: ");
  for (int i = 0; i < mfrc522.uid.size; ++i) {
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void setup() {
  Serial.begin(9600);
  while (!Serial); // Wait for serial.
  SPI.begin();

  mfrc522.PCD_Init();
  Serial.println("Initialized...");

  // default access key STANDARD KEY 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  for (int i = 0; i < 6; ++i) {
    key.keyByte[i] = 0xFF;
  }
}

void loop() {
  if ( ! mfrc522.PICC_IsNewCardPresent() ) {
      return;  // No card present, continue.
  }
  if ( ! mfrc522.PICC_ReadCardSerial() ) {
      // On success this function will return 1 and set the uid struct mfrc522.uid
      return;
  }

  printCardUid();

  // Write data to block.
//  writeBlock(15, writeBlockContent);
//  if ( readBlock(13, readBlockContent) == MFRC522::STATUS_OK )
//    printReadBlock();

  dumpCard();

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

And I quote:

With each memory access the internal logic verifies the format of the access
  conditions. If it detects a format violation the whole sector is irreversibly blocked.

The only thing that can get you locked out of a sector is incorrectly formatted access bits. As long as you didn't touch those, the sector should still be accessible.
It looks like you tried to change key A and key B. With the transport config, the contents of the sector trailer can only be altered if you authenticate the sector with Key A. Is that what you did? Lets continue then. Since you left the access bits unchanged (right?), it means only key A has R/W access to all blocks (except the manufacturer's) and key B, since it's still readable, can be used to authenticate but can't be used to access blocks. So, if your key change was successful, then you should be able to access the sector with your new key A i.e. {0,0,0,0,0,0}. If it wasn't successful (maybe because authentication failed), then the default key A should still be valid.

I tried accessing with A but I still get timeout in communication. Here's what was before in the trailer block:

Block 11 0 0 0 0 0 0 FF 7 80 69 FF FF FF FF FF FF

I've tried login with both key A being {0,0,0,0,0,0} and {FF,FF,FF,FF,FA} but it doesn't work. I can read the other blocks using key A {FF, FF, FF, FF, FF, FF }

@Metonymy Have you tried using the default key A? Wheres the code you used to change the keys? Edit your post.

I've tried used the default key, I can only read the other sectors with it.


text:
Matlab interfacing with arduino ERROR
I installed the MATLAB support package for arduino in my MATLAB r2013a today.
Now I plugged on my Arduino in my usb port.
And ran the command:

a = arduino()
Error: Undefined function or variable 'arduino'.

When I get:

a = arduino('COM18')
Undefined function 'arduino' for input arguments of type 'char'.

I have checked that this package has been installed.

It is grey.

Any help will be appreciated.
Thanks very much
Anupam.

Is the directory where the arduino package is installed added to the matlab path?

I a newbie to matlab. Can you please eloborate.I did not change any paths while installing.It was the default one.

Navigate to the package install dir in matlab and right click you should see the add to path option there. If the dir is on the Matlab path it wont be greyed out

actually theres a separate Arduino site on stack exchange you might find better help there

It is grey.See edited question

Arduino support within MATLAB came with Matlab-2014a onwards, you are using R2013a
Arduino support within SIMULINK came with Matlab-2012a onwards
for your release you can only interact via a simulink model

source: Stack Exchange

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

sort: votes


text:
Arduino Micro Power Questions
I have a few questions about the Arduino Micro circuit:

If I can provide a steady 5 V source (connected to +5V), then I don't need to use the voltage regulator module (including the selector) of the circuit. Correct?
If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?
If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?
If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

Schematic below for reference:

Is this a question about circuit design, as in: designing your own board which is nothing to do with a Arduino Micro?

Yes and no. I will be making the Arduino Micro circuit, but without the regulator module and voltage selector. But I want to make sure that this is actually possible to do, before I move on it.

If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

If you are powering off USB leave everything alone. See the schematic:

The blue line added by me shows what is going on. The VBUS signal from the USB connector goes through a 500 mA resettable fuse (to protect the USB port from overloads). Then it goes to the P-channel MOSFET (FDN340P) which makes a decision about whether to switch on and connect VUSB to +5V signal. It does so if VIN is low, making the MOSFET conduct. If VIN is high (which it would be if you had power into the VIN part of the board) then it disconnects the USB from the +5V line.

If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?

Definitely not. The 3.3V line is an output from the 3V3 voltage regulator. To connect it to ground would heat it up and destroy it.

If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?

No, VIN is already connected to ground via a 10k resistor (see schematic above) and thus it is not floating.

The picture helps a lot in terms of clarification! So if we take out the selector circuit, then I would have to connect +5V and VUSB manually, correct?

You might want to leave the fuse in, but yes, that sounds right. You could omit the 3.3V regulator too if you don't need 3.3V. The standard for USB is 5 V ± 5% which is within spec for the processor. I have made plenty of boards up where I just connect up a source of 5V to the Vcc pin of the processor chip. Make sure you leave in the decoupling capacitors on Vcc and AVcc.

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


text:
Gradual change of PWM motor control
Can someone please tell me what I'm doing wrong?
The motor's not turning at all, never mind changing speed.

Please post your code (copy and paste) - not a screenshot of it. That we we can try it ourselves, or copy an offending line. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

It looks like you are attempting to perform hardware PWM on an Analog Input Pin.
Assuming that you are using an Arduino Uno, try changing your first line of code to use one of the digital output pins which support PWM. You can use any of pins 3, 5, 6, 9, 10, or 11. Then connect that pin to your motor. (Note that you will likely have to use a transistor or driver circuit between the pin and the motor since the motor may well require more current to operate than the Arduino output can directly supply.)
If you are using a different Arduino other than the Uno, look at the documentation to find one of the PWM pins and try using that.

It's a pretty small motor that I took from an old printer. It runs off of the 5v and the 3.3v pins and from the analog pin when I analogWrite 255 or a bit lower. Admittedly it won't run at low analogWrites like 50. It's a clone Arduino Mega.

@GarionBracken: If you try to analogWrite() to a pin that is not PWM-capable, you will get either 0 (if writing less than 128) or 5 V (if writing something ≥ 128). What you wrote is essentially equivalent to digitalWrite(motorPower, motorVoltage >= 128 ? HIGH : LOW);

You should copy and paste the text of the code into your question, not a screenshot of it. Then we can copy and paste the problem lines into the answer.
You are varying up and down the variable motorVoltage in two loops. However you are not then doing an analogWrite with the new value. It should be more like this:
while (motorVoltage <= 255)
  {
  analogWrite (motorPower, motorVoltage);
  motorVoltage++;
  delay (200);
  }

A0 is an analog input. You can't output from it. You can only output on analog input pins by using defining them as 14,15,16...
For the best result, try changing the motor pin to something like pins 9, 10 or 11. They are my favorite PWM pins.

Guys I've moved the pin to one of the PWM pins and it's still not giving me any gradual changes. Also weirdly I'm able to manually set the analogWrite for my analog in pins and get lower output voltages. Noone seeing anything wrong with my code?

Yes, you are not doing the analogWrite inside any of your loops. All you are doing is changing a variable.


text:
Problem stopping a stepper motor with an endstop
Basically I have created the following code to control my stepper motor:
int pin_enable_motor_x = 38;
int pin_motor_step_x = A0;
int pin_direction_x = A1;
int endstop_x = 3;

void setup() {
  pinMode(pin_enable_motor_x, OUTPUT);
  pinMode(pin_motor_step_x, OUTPUT);
  pinMode(pin_direction_x, OUTPUT);
  pinMode(endstop_x, INPUT);

  digitalWrite(pin_enable_motor_x, LOW);

  for (int i = 0; i < 200000; i++) {
    runMotorSingleStepX(100, false); // runMotorSingleStepX(int delay, boolean direction)
    if (digitalRead(endstop_x) == true) {
      break;
    }
  }
}

void loop() {

}

void runMotorSingleStepX(int wait, boolean value) {
  digitalWrite(pin_direction_x, value);
  digitalWrite(pin_motor_step_x, HIGH);
  delayMicroseconds(wait);
  digitalWrite(pin_motor_step_x, LOW);
  delayMicroseconds(wait);
}

The idea is that the stepper motor will give many single steps until it reaches my mechanical endstop. But what really happens is that it detects true random pulses even when my endstop isn't pressed. So my motor stops before the point it should stop. I'm not sure if it's a common problem and I should be using some tricks to fix this problem.
Does anyone know what could be happening supposing that my electronics circuit is properly settled?

How is this endstop switch wired exactly?

I'm controlling a RAMPS board (http://www.reprap.org/wiki/File:RAMPS1.4schematic.png)... It happens with all endstop min (3,14,18) and max (2,15,19) pins... I believe that it's some kind of noise problem that's possible to treat by software because the Marlin firmware ( the official firmware that runs with the Arduino Mega and RAMPS) works fine.

Try making the endstop mode INPUT_PULLUP

It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Try a capacitor (eg. 0.1 µF) between the switch pin and ground.

Thanks, the extra 10K resistor solved the problem :) ...

Answer based on comments originally under the question
It sounds like the endstop switch may have floating input. Try making the endstop pins INPUT_PULLUP rather than INPUT.

It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Over a long wiring run the inbuilt 50k pull-up may not be strong enough to counter noise in nearby wires.

Thanks, the extra 10K resistor solved the problem :)

Your for() loop is using an int type for the iterator. You are asking it to run for up to 200,000 steps but an int is a 16 bit signed entity (~+/-32,768) so the for() loop will exit well before it reaches your desired count. That may be why you are not reaching the stop while still in the loop.
You may want to use an unsigned long as the type for your loop counter and or use a while() construct in which you incorporate the exit condition.

That's true, thanks ... But actually I wasn't using the 200000 max value. I just put a huge number there to make tests. Even fixing the int value my endstop is still detecting random pulses along the way and stopping before my motor reaches it.


text:
ESP8266 Programming using ESP-01 to USB converter
I am new to ESP8266. To ease out the task of programming esp8266, I bought this:  ESP-01 ESP8266 Programmer CH340G Chip USB WiFi Wireless UART GPIO0 Adapter.

Configured Arduino Interface to run AT commands in the serial monitor.
I flashed ESP8266 with the basic blink LED example. It worked fine for some time and later on gave this error.
warning: espcomm_sync failed

When i tried to flash another program on to ESP8266, I am getting the following error.
Sketch uses 221,995 bytes (51%) of program storage space. Maximum is 434,160 bytes.
Global variables use 31,568 bytes (38%) of dynamic memory, leaving 50,352 bytes for local variables. Maximum is 81,920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I could only find one article regarding this adapter.
There he made a custom bridge soldering GPIO 0 to GND for ESP8266 Flashing.
So should i make a removable bridge for the same, to upload a new program.
Is there any other way to simplify this task?

Thank you for the post you made! You should auto-answer this post with the post link "Check how to solve it [here]" and mark it as the correct answer.

I have this exact same module and what really puzzles me is that someone designed and manufactured this product, which simply does not work as advertised.

I know this is an old post, but I just recently tried to use this adapter myself and ran into the same issue. I was able to modify the adapter to use it for flashing the ESP-01.. For all of you still looking for answer, I've written instructable here https://www.instructables.com/id/USB-to-ESP-01-Board-Adapter-Modification/

Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip
For more info

Additional Reference:
Programming ESP8266

Many thanks, you saved me a lot of time! Btw an even simpler way would be fitting a small copper wire plugged in gnd and gpio-0 and then putting the esp01 on top of it

Just solder a jumper to the adapter according to this image (bottom side):

If you want to use programming mode, just switch to connect GND and GPIO0. Switch back to use GPIO0 as IO pin (you may attach your F-F Dupont cable to the floating pin).

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


text:
Controling pump while displaying moisture value on a LCD at the same time with soil moisture sensor?
I'm new with Arduino (and I'm not very good at English). Recently with Arduino Nano I have tested:

Control water pump based on soil moisture (using relay) (1)
Display soil moiture (in percent) on a Nokia 5110 LCD   (2)

Now I'm combining 2 codes to control water pump while always displaying moisture value (in percent) on LCD. However, after I have uploaded the code an Arduino Nano, the LCD showed nothing.
When I touched the sensor (changed moisture value) the first time, the LCD showed up, but when I touched the sensor the second time (changed moisture value again), the LCD went blank. The relay and pump still work fine, so I think the problem comes from LCD's code.
Here's my code (1):
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250;

void setup()
{
  Serial.begin(9600);
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop()
{
  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(RELAY1,0);           // turn on relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(RELAY1,1);          // turn off relay
    Serial.println("Light OFF");
  }
}

The code (2)(got it from the Internet):
    //////////////////////////////////////////////
   //        Arduino Soil Moisture Sensor      //
  //            with NOKIA 5110 LCD           //
 //           http://www.educ8s.tv           //
//////////////////////////////////////////////

#include <LCD5110_Graph.h> // THE LIBRARY I AM USING IS THIS:  http://www.rinkydinkelectronics.com/library.php?id=47

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int sensorValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup() {
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop() {
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48);
  sensorValue = analogRead(sensorPin);
  percent = convertToPercent(sensorValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update();
  delay(1000);
}

int convertToPercent(int value)
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length)
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

And my combined code:
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250; // Mức độ ẩm cố định là 250
#include <LCD5110_Graph.h>

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int MoistureValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup()
{
  Serial.begin(9600);//Mở cổng Serial ở mức 9600
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode (12, OUTPUT);
  pinMode(RELAY1, OUTPUT);
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop()
{
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48); // hiển thị giao diện màn hình
  MoistureValue = analogRead(sensorPin); // đọc giá trị từ cảm biến

  percent = convertToPercent(MoistureValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update(); // cập nhật màn hình
  delay(1000); // mỗi 1 giây

  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(12,HIGH);
    digitalWrite(RELAY1,0);           // bật relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(12,LOW);
    digitalWrite(RELAY1,1);          // tắt relay
    Serial.println("Light OFF");
  }
}

int convertToPercent(int value) // đổi giá trị cảm biến sang phần trăm
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length) // hiển thị phần trăm ra màn hình
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

Any advice?

include a circuit schematic, preferably fritzing

I think the problem is with
digitalWrite(12,HIGH);

and
digitalWrite(12,LOW);

Pin 12 is used by the LCD. Changing it's output will reset the LCD. I'm not sure why you put it there to begin with, as it wasn't part of any of the two sketches.

Thank you Gerben. Pin 12 I used in code (1) as a led to indicate if the pump was activated. I though I have deleted it in the last code but turn out I deleted it in code (1) instead. That's why you though it wasn't part of any sketches. What a simple mistake haha. I don't have time to check it right now but it must be the answer. I'm going to check it and close this question in few hours later. Btw this website don't have section to add comment for answers? I can only add comment for questions

@LêThànhVinh you just commented on an answer. For your own question, you can edit it

in cases like this where you are combining multiple pieces of code together, a simpler approach would be to rename that:
//set up 1
void setup1(void) {
...
}

//loop 1
void loop1(void) {
...
}

//set up 2
void setup2(void) {
...
}

//loop 2
void loop2(void) {
...
}

...

//combined setup
void setup(void) {
  setup1();
  setup2();
  ...
}

//combined loop
void loop(void) {
  loop1();
  loop2();
  ...
}

that's much easier to track than to manually copy-and-paste them.

authors: علي ود هندسة


text:
How to correctly read a string from Arduino serial port?
I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

server.listen(8080);
app.use(express.static('public'));

var brightness1 = 0;
var brightness2 = 0;
var string;

io.sockets.on('connection', function (socket) {
    socket.on('led', function (data) {
        brightness1 = data.value1;
        brightness2 = data.value2;
        string = brightness1 +","+brightness2;
        var buf = new Buffer(1);
        buf.write(string);
        serialPort.write(buf);
        console.log(buf);
        console.log(string);
        io.sockets.emit('led', {value1: brightness1, value2: brightness2});

    });

So based on that, I'm sending a string over the serial and the console log showed above gives me that:
<Buffer 32>    //console.log(buf);
23,0           //console.log(string);

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the
Arduino side I used the sketch provided here and retouch it a bit based on my needs:
void setup()
{
  Serial.begin(115200);
}
void loop()
{
  while(!Serial.available());   //wait until a byte was received
      Serial.println(Serial.read());
      int a = Serial.parseInt();
      int b = Serial.parseInt();
      Serial.println(a);
      Serial.println(b);
      //analogWrite(3, a);
}

but the result of my Serial.print() are really incongruents, something like:
5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?

You sized your buffer with room for one single byte: it only gets the '2' of "23,0". The ASCII code for '2' is 0x32 (in hex). That's the meaning of <Buffer 32>.

@Edgar thanks for your reply! So basically my problem is on server side, so I just need to increase the buffer size to 7? Arduino side is all good right?

There is a problem server side, but then I am not sure how well the Arduino side would perform, especially if you don't control the timing of the sent bytes.

This is a common (and my favorite) approach:

Choose an “end of message” character. CR or LF can be good choices,
especially if you want to test your program with a terminal emulator.
On the Arduino, buffer all the received bytes until you see the end of
message.
When you see the end of message, handle the buffer to a function that
will parse and process it.

I would avoid parseInt() for anything but the simplest tests, because
it is both blocking and sensitive to the timing of the input.
For an example, you can take a look at this
Simple Arduino command line
interpreter
(look at loop()). It's non blocking, so you can add background
processing to perform while waiting for input characters.

I fully agree here with edgar Bonet.
I only want to add a link to a library I have written that does a line by line (based on end message CR and/or LF)
SerialStringReader
This library contains examples.
Note that for many reasons the library uses null terminated strinsg (also known as char arrays) and not the Arduino String class

How to correctly read a string from Arduino serial port?

You can use the function Serial.readString(). It will return a string that you typed from the serial monitor.

No, really. This way you will only get what is in the buffer now. If you read faster than the other end writes you will get just a piece


text:
Using pointers with Arduino
I am learning about pointers.
I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use Serial.print( (long) &ptr1, DEC); and Serial.print( (long) &ptr1, HEX);
 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10;
   float test2 = 3.14159;
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2;
 char *ptr3;
  ptr1 = &test1;
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");
  Serial.print( (long) &ptr1, HEX);

  }
 void loop() {

    }

My output is:
The integer value is stored in  2296
The integer value is stored in  8f8

You realise you're printing the address if ptr1 here, not the test value (I think...) The formatting shouldn't make any difference - can you add example values that you get (when you print both values in the same program, re-compiling could potentially move these locations.

@Sean I have edited my question. It gives me 2296 when I put decimal format and 8f8 when I put Hex format

"Why do programmers always mix up Christmas and Halloween? Because Dec 25 is Oct 31" in your case "DEC 2296 is HEX 8f8".

You're printing the address of the pointer, not the contents of the pointer.
Say you have the memory map of:
100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

test is located at address 100 and takes two bytes. ptr1 is located at 102 and takes two bytes. ptr1 contains the address of test (100) and test1 contains the value 20.
The different possible combinations of prints are:
Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a cast in order for the C++ to select the correct println() overload function.)

Serial.print would not work for &test, I had to put (long) before that. I get different results for Hex and Dec. I have edited my question.

I purposely omitted the casts that you would need to get the right println overloads so it didn't get too cluttered. That doesn't make any difference to what is happening though. You need to learn just what & and * mean.

so 2296 is the same as 8f8 with different format?

You're trying to play with pointers and you don't even know the difference between decimal and hexadecimal...?!?!

so 2296 is the same as 8f8 with different format - yes. Google 0x8f8 in decimal. You can get calculators that will do that for you. Probably is one built into your PC.

When you Google that Google even hands you a calculator right there in your browser.


text:
Inconsistent response AT command
I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters
Response
+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20
Expected response
+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,
Code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); //RX, TX

String inputString = "";
char inChar;

const int powerkey =  5;
const int statuspin = 6;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(powerkey, OUTPUT);
  pinMode(statuspin, INPUT);

  mySerial.println("AT");
  delay(2000);
  leserial();

  //TURN ON GPS
  mySerial.println("AT+ CGNSPWR =1");
  delay(2000);
  leserial();
}

void loop() {
  //GET LOCATION
  mySerial.println("AT+CGNSINF");
  delay(4000);
  leserial();
  delay(5000);
}

void leserial(){
  inputString = "";
  while (mySerial.available()>0){
    inChar = mySerial.read();
    inputString += inChar;
  }
  Serial.println(inputString);
}

Rookie mistake with serial reading. This explains: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

I want to know which clown first advocated blindly sending commands and delaying for 2 seconds to wait for a response. I see it so often it must be in some tutorial somewhere. Is it on Instructables? Youtube? Both are as bad as each other for spreading misinformation...

I managed to solve the problem, I edited the file "SoftwareSerial.h" and changed the size stated in constant _SS_MAX_RX_BUFF.
#define _SS_MAX_RX_BUFF 64 // RX buffer size

to:

#define _SS_MAX_RX_BUFF 128 // RX buffer size

I reached the conclusion that when I realized that the number of bytes returned in the function "mySerial.avaliable ()" was no more than 63 bytes.
I appreciate the support of all.

I am not sure if it is a good idea to patch the Arduino library as a workaround for your poor code.

Basically you're sending a command that gives a response, then waiting 2 seconds for that response to arrive (which is completely the wrong thing to do to start with).
You have to ask yourself: where does that response go when it does arrive, while it's waiting for you to finally get around to reading it?
The answer is: into a small internal buffer that is considerably smaller than the response.
Thus most of the response just gets thrown away because there isn't room for it.
Instead you should most definitely NOT delay for 2 seconds waiting for the response, and instead keep looking to see if there are any characters to read up until you reach the end of the line.
It's all explained here: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Thanks for the tips, really using the "delay ()" to simulate waiting for the command to be run completely is quite common in the tutorials on the internet. Everyone who saw makes use of this function! Your article helped me better understand the operation of the serial communication, but applied some concepts that you had not got success, the answer still comes incomplete. As you mentioned in answer, apparently the buffer does not contain the size of the command response. I increase the buffer size?

If you remove the delay and read the bytes as they arrive the size of the buffer is irrelevant.

I removed the sleeps but did not work. Any idea what could be? Thank you for your support.

If you show your new code we might be able to see where you are going wrong...


text:
Print when echo is read by HR-S04 sensor
I'm trying to see when an echo is received by my HR-S04 sensor. I have a Serial.println within my while loop to read the signal and see once a change happens to break the loop.
The issue is my serial just prints out the pin my echo to linked to. How can I set it so that the serial output is LOW and then HIGH once an echo is received?
int trig1 = 3; //Trig 1
int echo1 = 4; //echo1
int ECHO1;
double pingTime1;

void setup()
{
  Serial.begin(9600);
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1); //assume echo1 is LOW and HIGH once echo is received

  while (ECHO1 == 0) //continuous loop until echo is HIGH
  {
    digitalWrite(trig1,LOW);
    delay(100);
    digitalWrite(trig1,HIGH);
    Serial.println(echo1); //Troubleshooting to see when pulse is read by sensor
   ECHO1 = digitalRead(echo1);
  }
  pingTime1 = pulseIn(echo1, HIGH); //Measure ping travel time in microseconds
  pingTime1 = pingTime1*1000; //convert microseconds to seconds

}

Umm, does your code wok in the first place???

To start with, you code isn't suppose to work. Here is a working code to start with (code below). You have a lot of mistakes so I suggest comparing your code to this one. Also, don't try to debug by adding a Serial.print(/*something*/); in your code.
For the time the echo is received is way too fast (under 0,001 seconds). I doupt you can use that for something useful. There is a way to calculate that using the millis() function, but it is quite complex for your project.
Here is a working code for the HC-SR04:
const int trigPin = 2;
const int echoPin = 3;

long duration, distance;

void setup() {

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

  Serial.begin(9600);
}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 150) {
    Serial.print(distance);
    Serial.println("  cm");
  }
  if (distance > 150) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

I'm trying to record the system time when object passes by the sensor. I plan on having another sensor a little further up to record a second time. I plan on finding final time by difference then distance between sensors to compute speed.

A couple things:
1) I believe your code for the trigger pin is wrong. An example I found sets it up as LOW for 2 microseconds, then HIGH for 10 microseconds, then LOW. (Note that the units are MICROseconds so you must use delayMicroseconds()
2) digitalRead(echo1) does nothing. Use the pingTime1 instead. You will always be receiving an 'echo' so it's not a HIGH or LOW but rather a changing variable stored as pingTime1.
3) echo1 is the variable for the pin. That's why Serial.println(echo1) prints the pin number. You could try Serial.println(ECHO1) but I don't think it will work because of what I said above.
4) If you want a HIGH or LOW to print to screen you must set a cutoff value for pingTime1 then use an if statement to print the appropriate value.
I'm not sure what exactly you're trying to do, but given the points above I do not believe a while loop is necessary.
Try this code. You can keep the first Serial.println() to see the duration of the pulse and/or you can keep the if statement if you want a HIGH or LOW to print to screen.
// Send a pulse out through trig pin
digitalWrite(trig1,LOW);
delayMicroseconds(2);
digitalWrite(trig1,HIGH);
delayMicroseconds(10);

//Receive pulse through echo pin
pingTime1=pulseIn(echo1, HIGH);
pingTime1=pingTime1*1000;

// Serial print
Serial.println(pingTime1);

//Serial print (for HIGH or LOW)
if (pingTime1 > cutoff) {
    Serial.println('HIGH');
}
else {
    Serial.println('LOW');

I'm trying to record the system time when object passes by the sensor. I plan on having another sensor a little further up to record a second time. I plan on finding final time by difference then distance between sensors to compute speed.

Okay, you might want to clarify the question in your post. Just use an if statement to 'trigger' the sensors. (if within certain distance, record time)


text:
Wake Arduino (Atmega328) from sleep with ADXL345 interrupt
So I'm relatively new to microcontrollers, and I'm having a problem implementing a feature I want for a project.
I've learned about putting an Atmega328P to sleep from this tutorial. I'm using an Arduino Nano, so I only get my current down to ~9mA rather than the µAs the tutor is getting. Nonetheless, it demonstrates the abstraction I want to learn for when I move to just the Atmega328 with no board.
I've learned to wake up my microcontroller from sleep with a falling external interrupt on INT0/D2 from a simple button. My ISR is empty and just boots me back to the loop, which is fine. As an aside, I have heard that it is better to have simple and short ISR's, but I am not completely sure why.
My question is, can I use my ADXL345 to trigger an interrupt that wakes my Arduino? I am semi-familiar with using an ADXL345 over I2C, although I don't understand why my Sparkfun ADXL345 requires different wiring than my unbranded one, but that's for a separate question I suppose.
So my question is, is it possible, and if so, how? Also, is the I2C connection meaningful for an ADXL345 that is primarily being used as a wake-up interrupt on the Z-axis only? (My use case is an item someone picks up, which wakes my embedded circuit out of sleep and begins logging load cell and UWB sensor data, and is put back to sleep after a period of inactivity).
Thanks in advance - I appreciate any and all help!

If you don't have anything in the ISR, you could use EMPTY_INTERRUPT(INT0_vect); instead. Secondly, the Atmega328P can wake up from falling edge interrupt to (though the datasheets states differently). What I sometimes to is disabled the INT0 interrupt inside the ISR, so it only fires once; then enable it again before I go to sleep. The accelerometer probably doesn't remember any settings, so you'd still need the I2C to setup the ADXL345 at power-up.

So I would have a setup function, a loop function, and an ISR. I would configure the ADXL345 in my setup, run a loop that puts my microcontroller to sleep, and use an ISR for when my accelerometer receives a double tap (for example). In the ISR, the microcontroller wakes from sleep, and I would also disable the interrupt, and point the program back to my setup to refresh my accelerometer setup, reattach an interrupt, and run the loop to go to sleep again. Does this sound correct?

Mostly, yes. You only need to setup the accelerometer once. By "power-up" I meant applying power. So e.g. when you insert new batteries.

Do you have any example code where you do this all?

When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant.  Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino.  Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.
On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino.  By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.
As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,

The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT_INVERT bit in the
  DATA_FORMAT (Address 0x31) register.
How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345.  You will need to configure the unit before it does anything, because it powers up into standby mode.  See the second paragraph of POWER SEQUENCING, page 13 in spec sheet, and see Table 6 on that same page:

At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.

When you say map the wake-up event to INT1 (digital 2) on the Arduino, do you mean in Arduino code? Also, how do I toggle bits in an ADXL345 - do I do it through my Arduino IDE?

@A.Orchard, please see added paragraphs at end of answer.  Also, I rephrased some 'map' refs, eg, “By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345”


text:
Change Digispark clock speed, run at low voltage?
I have a low voltage (3.2v) application. I was hoping to use the Digispark. I have a solution using a separate Tiny85, but want to use the Digispark USB programming.
To run at lower voltage I think you need the lower clock rate. I have done this using the standalone Tiny85. I could hook up the Digispark to the programmer direct and change the frequency fuses, however...
I assume reducing the clock rate by programming the fuses would break the Digispark boot loader as it would have the wrong timing. Correct?
Can I dynamically switch the clock frequency in my code after the bootloader or is it fuse controlled only?
Is the bootloader available and could I change it to a lower frequency? Would there be a lot of work changing the code to a different freq? Would it be powerful enough to run the USB bootloader?

You can set the clock prescaler at run time. For example:
#include <avr/power.h>

void setup()
{
    clock_prescale_set(clock_div_8);
    // etc...
}

More details in the documentation from
avr-libc.
Note that with this method your Digispark will still be overclocked when
booting, so it might not be 100% reliable. But it will be overclocked
only for a very short time.

I was kind of hoping it would hobble through the boot loader over clocked as I do not need it to actually connect to usb at the low voltage.

@BillyBag2: I would expect it to work. See the answers to this related question: Arduino 16 MHz with only 3.3V?.

Thanks Edgar, This was useful for me for a Digispark ATTiny85 (china clone) that is talking I2C to an ESP8266 NodseMCU v3 Lolin. I have divided by 4 and still works. The ATTiny´s own current consumption has lowered from 11.2mA @16Mhz to 5.6ma. The ATTiny is powered 3.3v from the NodeMCU's regulator 3.3v output to it's 78L05 (output).
I have disabled both LEDs with two, almost invisible, small cuts in the PCB, i could re-solder if necessary.
I am using Rambo's TiniwireS library for I2C. Thanks again.

The digispark uses the micronucleus bootloader.
You can flash that directly onto an Tiny85 without needing the digispark module. So your existing Tiny85 solution could acquire the USB bootloader if you can spare the 2k program space for the bootloader.
I realize this is not a direct answer to your question, but you did note that you have a Tiny85 solution and wanted USB bootloader support on it.

Maximum safe frequency at 3.2V is around 12.7Mhz. See figure 20-2 in the datasheet.
This is indeed lower than the 16MHz the digispark is running at.


text:
Do I use an Arduino or an ARM based Launchpad board for my commercial project?
I want to use a board for an Industrial Project, which is based on temperature sensing, sharing and data storage.
Which board do I use?
Will it be reliable for a long span of time?
Will it be foolproof?

Neither: use a PIC32 based chipKIT board. But then that's just my opinion, just like every other answer you will get to such a question.

Microcontrollers are basically made to run "forever". But where/how are you sharing/storing data? Just sensing temperatur and sending it over RS485 (common in industry) can be achieved by making your own board, but you'll have to be sure that it can resist voltage spikes etc. Also your code has to be able to recognize and act upon errors.

Adding to Candice the Cyborg's answer above.
Which board do I use?
Since its a commericial project you are going to sell then -I would say the right answer is the cheapest ARM or Arduino based board (when migrated to breadboard) to make your project.
Will it be reliable for a long span of time?
For reliability ARM and arduino would be reliable-they are after all both professional engineering products-and both can be used to make commercial products. I am assuming can be sure that your software for the ARM or Arduino is not buggy and professional-thus there is no reliability issues from the software. The span of time that the arduino can retain information reliably is given  in the data sheet-I think its about 100 years.
Will it be foolproof?
Yes if you can be sure that you get the hardware design correct and the software correct-I would imagine this is where a problem would probably come from for your device.

If you are want to be professional, make a custom PCB. This lets your project be neither and also stronger. This also makes you look like you actually spent more time on the project and make it great for industries.
If you still want to use an Arduino based board, you might as well use an Teensy 3.2. They are small, powerful and are still at a low price. Buy it here.
If you make a good case for your project, it could last quite a long time. It might even last many years of continuous run outside at unregulated temperatures. Just make sure it doesn't get in contact with water or high levels of humidity and you should be good.

thanks for the advice. Seems quite reliable. I think I will make a custom PCB then. Now my question is, which processors do you think are reliable? ARM processors or the ATMega based ones?

A couple of sensors or a simple circuit will run fine with an ATmega. Want more power, a more reliable and fast processor use ARM. An ARM is better in everyway except the price and the simplicity.

All processors are reliable. It's the software that people write to run on them that isn't.


text:
Getting an error while uploading a code to the Arduino when ethernet shield is attached
I bought ethernet Shield today and connected it to Arduino Uno, now when I try to upldoad I get the following error, however if I remove the shield from the UNO it works fine.
Sketch uses 10,486 bytes (32%) of program storage space. Maximum is 32,256 bytes.
Global variables use 661 bytes (32%) of dynamic memory, leaving 1,387 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

Is it something wrong with he ethernet shield ?
Ethernet is not plugged in but even when i plug in the ethernet wire the indicators at Jack does not lit up

Unplug your ethernet shield. Then upload your program. Plug in your ethernet shield  and check if your program is working fine. If your program is not working as expected, there may be some issues with the shield.

I have tried that already it didn't helped

What was not working. Your program was not working or you were getting errors uploading code.?

Error uploading code when shield is plugged in

Upload the code and then plug in your shield. Then check if your uploaded code is working correct or not.?

I have tried that already , then nothing comes in serial monitor tried all baud rate

If you are sure enough that all the connections and your code is correct, that means your shield is not working.

I learned yesterday late night that it's duminloev shield while I have UNO R3

I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.


text:
Arduino ESP8266 Webserver
What I would like to do is control my garden lights using the ESP8266. For this I use the Arduino approach from here. This works great, I use bootstrap and jquery even :D all is well!
Switching lights on and off using my code is fine but now I'd like to switch some continues routines, like blinking. I can start the blinking from the webpage but this code is a loop so I cannot get back to turn it  off again.
I could make it blink for a set amount of loops, so eventually it will stop blinking and show the control webpage again.
Or I can add the blinking to the hardware, maybe use a 555 for the first time?
But there might be a better way of implementing this..
Using Google I found information about Break and Interrupts, not yet what I am looking for.
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char *ssid = "mynetwork";
const char *password = "mypassword";

ESP8266WebServer server ( 80 );

const int led = 5;
String webPage =
"<!DOCTYPE html>\
\
\
  <title>Funny Bunny Control</title>\
  <meta charset='utf-8'>\
  <meta name='viewport' content='width=device-width, initial-scale=1'>\
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>\
  \
  \
\
\

\

\

Funny Bunny v0.1
\

\

Omdat snuffelen er bij hoort.
\

Niet voeren aub.
\

\

aan
\

uit
\

\

\
\
";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void aan() {
  digitalWrite ( led, 1 );
  server.send(200, "text/html", webPage);
}

void uit() {
  digitalWrite ( led, 0 );
  server.send(200, "text/html", webPage);
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  digitalWrite ( led, 0 );
  Serial.begin ( 115200 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );
  server.on ( "/aan", aan );
  server.on ( "/uit", uit );
  server.onNotFound ( handleRoot );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop ( void ) {
  server.handleClient();
}

Take a look at the SimpleTimer [http://playground.arduino.cc/Code/SimpleTimer] library in the Arduino IDE environment.
You can have timers to:

call a function at a consistent interval,
call a function once after a set delay,
call a function a set number of times with a consistent interval
between.

Looks great! It works fine but I cannot get the timer to stop, I can name the time and disable it I guess but the documentation does not show how to type the variable that holds the timer. something like this? int blinky = timer.setInterval(1000, RepeatTask);

The type of the timerId is int. You could call timer.disable(blinky); to turn off one repeating timer.


text:
Is there a way of turning a computer into a Arduino type board?
The Arduino's processing power is not sufficient for some of the tasks I would like it to perform...
I'm thinking of making a Home Automation System and would like some serious processing power at the center of it all.
So I'm wondering if I can just use standard PC parts to essentially put together my own board?!?
Is this possible???

Is there a reason why you can't interface with the Arduino but process with the computer?

Just connect an Arduino to the PC and do the heavy processing on the PC  and then tell the Arduino over serial what to do. Or use something like an Raspberry Pi. But it really depends how your home automation system is set up. If you are communicating with your other devices over WiFi or Bluetooth you just need a normal PC with WiFi/Bluetooth. What do you actually want to do with a powerful "Arduino", that you can't do with just a PC/Arduino?

Why not use standard PC parts and make a PC?

The old IBM PCs ran at 4.77 MHz. Your Arduino runs at 16 MHz. I'm a little sceptical that it can't keep up with turning on and off your lights in a timely way.

If arduino is not giving you serious processing power, you can use Raspberry pi, beagle board, toradex board to make your own embedded PC. I guess these are enough for your application

An mbed board would give more cpu power (most are in the 100MHz Arm M3 region, some are slightly faster M4s) while staying bare metal like an Arduino. If that's not enough I'd agree with a Pi rather than a PC.

For home automation, it IMHO makes sense to have a central "server" (raspberry pi is enough) that can serve webpages. This webpage would be connected to a "gateway" that can send TCP/IP (or http) commands to Arduino's or ESP8266’s. This way, you can make use of your existing network or wifi. The Arduino/ESP8266 will be vast enough to read a message, change an output according to the message and return an "OK". Which is all you need on an endpoint.

A regular Arduino uses an AVR, more "pimped" Arduino might go to ARM. Some special versions of Arduinos uses other chips, such as the ever iconic ESP8266.
For home automation, an ESP8266 is WAY enough. Using an ARM is quite and overkill for home automation. But I've never seen anybody using a full PC for it. Why? Because it is around 10-20 times more expensive. They require much more components and many other things.
Something close to a full PC that you can get is a Raspberry Pi (any version would do). They act like a small PC, some even use it as a laptop. See PiTop. The Raspberry Pi is stronger, more powerful, and much faster then any Arduinos. The Pi also has ethernet, a graphic interface, and an audio interface built in. That means that you can pretty much connect it to a monitor and it will work as a normal PC running either Windows or Linux. You can then watch a video, with graphics and sound, from the inthernet without external modules like you would need on an Arduino. Their only weakness is that it is harder to program them to read may sensors. That is why the Arduino is popular for covering that.
At the end of the day, it is your choice. I would personnally suggest an ESP8266. This module has many GPIOs, depending on the breakout that you have, and has WiFi built in. This is a great feature for home automation. Most home automation builders use this module.
If you have any questions about the informations I just gave you, comment it, I'll reply.

I assume he wants to make a controller with a WebUI/GUI and stuff. A ESP8266 won't be enough for that.

@gre_gor, actually, the ESP8266 can do a small web server with a VERY simple UI.

One of the Arduino ESP8266 examples is a web server with uploadable files (in SPIFFS). Adding the appropriate routes is all it takes to make a decent web controller.

You could simply opt for a different platform? A Raspberry Pi or Beagle Bone? Either would probably have enough processing power and ram. The Onion Omega2 is a SoC with a 400Mhz CPU, 64MB of DDR2 RAM, 16MB of on-board flash storage, 802.11b/g/ WiFi at 150 Mbps, 18 digital GPIOs, I2C, SPI, and USB2.0, a full Linux Operating System, and it costs $5.
The Onion Omega

Adding to Candice the Cyborg's answer I would go for esp8266-12 (for a specific breakout board) if you choose to go down that route-where Candice the Cyborg writes " "pimped" Arduino" this does not refer to the esp8266.
But if you're using a PC to begin with you might as well get a PC based hardware to do the home automation. Arduino can't compete with PC for power and features-but it was never designed to.
You could try linking multiple Arduino's together communicating through the serial port pins-essentialy it would work something like a parallel processor. If it's just run of the mill home automation things then this can be broken down into a parallel problem. If you update your question with more info I can give you a more specific answer. I mean if your tasks only require a little extra processing power then it may be possible to do using an addition Arduino for example.
The cheapest way to set up a PC for home automation is probably add in a parallel port card-there are project around the internet that show how to use a PC for home automation with parallel port-if you don't have a parallel port then you can get a parallel port card for less than $5-so its cheap way to get IO pins-this was the way things could be done before the days when Arduino existed.
Using an Arduino UNO or the like is not a good idea for interfacing to USB devices -like cameras -if you has that in mind- that's because the ATMEGA chip does not natively support USB host and it's non-trivial to implement USB interface host yourself on Arduino-it would take deep knowledge of USB protocol as a minimum.
Sorry to say it on an Arduino site- but it may turn out cheaper to use a full PC (if your project can be run on an old PC you can get cheap or free) with no Arduino- a PC after all has much more hardware already built into it -lots more ports, video output and so on. Adding the cost of shields to do something similar on Arduino could cost a lot-it depends on the specifics of your question -which you don't give.

One thing a PC lacks, which is kind of critical for working with sensors and things, is easy access to IO.
A PC has a number of buses, but no GPIO pins. To get any form of GPIO you will have to add extra hardware in the form of PCI cards, etc. Those kind of things, since they are not widely used, are rare and hence expensive.
People have "hacked" their PC hardware before now to add I2C devices to the I2C bus that is present on all DDRx DIMM slots (used for module identification) and using that you could add I2C IO expanders to get some GPIO pins - however that is not easy to do, and then you have the problem of programming it on top of that.
The most flexible solution is to use USB. Using the PC as the "core" processor for heavy data processing, image capture, network communication, etc is simple enough and commonly done. Then using USB you interface to the devices you want to work with - cameras, etc. You can get USB-based IO boards which provide different forms of IO communication, such as TTL UART (FT232 boards, etc), parallel GPIO, I2C buses, SPI, etc. Of course, programming those things becomes somewhat tricky, and you may end up with a massive number of dongles on your computer to interface with the large number of things you want to connect to.
So a more flexible and sensible approach is to create your own USB interface to your sensors and other items. And one of the best and easiest systems to do that is, of course, the Arduino and Arduino-like boards.
An Arduino, or multiple Arduinos, become a sensor interconnect board which you program to communicate with whatever you need to communicate. That can then pass data back to the PC through USB which then performs the heavy number-crunching and what have you. Data can then be passed back through the USB to the Arduino for controlling other things (fans, lights, heaters, whatever).
So yes, you can use a PC as a powerful processor system in a larger plan, but the PC itself cannot replace an Arduino.
Of course, all this is assuming you have a PC to waste on the project, or you have the requirements of massive amounts of processing power that you can't get from any decent micro-controller or SoC.
One thing to remember: there are micro-controllers available cheaply today with considerably more power than the first pentium PCs - I regularly work with 200MHz MIPS based MCUs with embedded FPU - that's 3.33 times more powerful than the first pentiums (and without the floating point bug ;) )
The current Raspberry Pi embedded Linux computers provide all the GPIO and interfacing you should need at a tiny fraction of the price of a PC. They are (as of version 3) a quad-core 1.2GHz 64-bit SoC. The same quad-core 1.2GHz core that is used in many smart phones. That's more powerful than my laptop.

One approach that I am using in a project right now is to use both an
Arduino Mega 2560 (for interfacing the hardware, as it has many
5 V GPIO pins, analog inputs and very predictable timings) and a
Raspberry Pi (for running a Node.js-based Web server). They
communicate through a level-shifted serial link, using a protocol
roughly shaped on this command line interpreter.
This way I have both the ease of interfacing hardware provided by the
Arduino and the power of a real computer.
Not saying it is the right solution for you, but as you did no provide
details on your project's requirements, we can only make suggestions.


text:
Arduino Pro Mini name in CMakeList.txt in CLion
I recently try to get my Arduino Pro Mini (5v 16mhz)running in Clion.
I tried to set up the CMakeList.txt but I get the following error:

Error:Can not find f_cpu in boards.txt for Arduino board ID (pro),
  aborting.

I used the following configuration:
set(${CMAKE_PROJECT_NAME}_BOARD pro)

In the boards text, located at C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I found the following lines:
pro.name=Arduino Pro or Pro Mini

pro.upload.tool=avrdude
pro.upload.protocol=arduino

pro.bootloader.tool=avrdude
pro.bootloader.unlock_bits=0x3F
pro.bootloader.lock_bits=0x0F

pro.build.board=AVR_PRO
pro.build.core=arduino
pro.build.variant=eightanaloginputs

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

So I'm wondering what Boardname to use, to get the Pro Mini working. Thanks in advance!

There is some pretty similar GitHub issue.

The problem here is that the Pro Mini comes in a number of variants for different voltages / speeds etc. The different variants are selected using a menu in the IDE.
CLion doesn't know about those menus, nor how to find the f_cpu from the right one for your board.
So there are two solutions:

Create your own board entry for the Pro Mini without the menu entries.
Use an earlier version of the IDE that has the Pro Mini boards as separate entries (basically any version before the menu system was created).

If you want the latest API then you will have to go route 1. That could be as simple as modifying the existing pro.* entries to remove the menu and replace that section with just the flags that are set by the correct menu (basically remove all the pro.menu.* entries except the ones for your board, then remove the menu.cpu.<whatever>. from each of the lines, as well as the entire menu entry name line.)
So you would basically change these lines:
## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

to this:
## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.upload.maximum_size=30720
pro.upload.maximum_data_size=2048
pro.upload.speed=57600

pro.bootloader.low_fuses=0xFF
pro.bootloader.high_fuses=0xDA
pro.bootloader.extended_fuses=0x05
pro.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.build.mcu=atmega328p
pro.build.f_cpu=16000000L

and delete all the other pro.menu entries.


text:
Problem fetching data from MPU6050
I am new to Arduino. I have an arduino mega board, which I need to interface with MPU6050 accelerometer-gyroscope module.
My connections are
Arduino_SCL->MPU6050_SCL;
Arduino_SDA->MPU6050_SDA;
Arduino_GND->MPU6050_GND;
Arduino_5 V->MPU6050_Vcc;
Arduino_Pin 2->MPU6050_INT;
I have uploaded the following code to the arduino mega.
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

MPU6050 accelgyro;

int16_t ax, ay, az, gx, gy, gz;
double  time;
int i;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  accelgyro.initialize();
  time = millis();
  i = 1;
}

void loop()
{
  // collect readings
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  // print result
  Serial.print(i);   Serial.print("\n");
  Serial.print(ax);   Serial.print("\t");
  Serial.print(ay);   Serial.print("\t");
  Serial.print(az);   Serial.print("\t\n");
  Serial.print(gx);   Serial.print("\t");
  Serial.print(gy);   Serial.print("\t");
  Serial.print(gz);   Serial.print("\t\n");

  i = i + 1;
  delay(1000);
}

My problem is when I observe the reading on serial monitor, it shows every reading as zero. Does this mean my sensor is damaged or there's some problem with my connection? Or is my code for fetching the data incorrect?
Thanks

Have you put pullup rsistors on SDA and SCL wires? I2C expects these wires to be pulled up. Some dvices include pullup resistors, but not all. For MPU6050 I don't know, but probably not.

@jfpoilpret, most MPU6050 breakouts have pull-up resistors. I did some research before buying mine and most of them have pull-up resistors.

If you are using the MPU6050 library from jrowberg/i2cdevlib, the library does not have any kind of error handling, so it is unfortunately not easy to guess what went wrong, or even if something went wrong. If the getMotion6 function fails, it will simply copy corrupt data into your return values and it is not possible after the invocation to tell if the function succeeded and you got a valid reading, or if the function failed and you only got garbage back.
One possible problem is that the MPU6050 can be configured to use one of two I²C addresses (0x68 or 0x69) and you are using the default address, as implemented in the MPU6050 library (0x68). It might be worth to try the other address, in case your module is configured that way:
MPU6050 accelgyro(0x69);

To change the module's adress, set A0 to HIGH.


text:
clkI/O 256 & 1024 (From prescaler) not working with driving PWM on Nano board
I've been working with PWM in TIMER0 of my nano board.
So, it's working now and I know how to set OCR0A or OCR0B.
Then, I went to play with Clock Select Bits CS02 CS01 CS00 in TCCR0B.
0, 8 and 64 prescaler configurations worked as I also don't see the effect on the LED fade speed.
But the more problem I get is that 256 and 1024 prescaler don't work at all and the LED goes on all the time.
What is the problem?
The code:
void setup() {
    DDRD |= (1<<DDD6);
    TCCR0A |= 0xC1;
    TCCR0B |= 0x00; // this works for 0x01, 0x02, 0x03 only
    }

    void loop() {
    uint8_t i;
    for (i=0;i<256;i++)
    {
      OCR0A = i;
      _delay_ms(1);
    }
    }

regards,

Do you have the real code? And if you are using Arduino framework, don't forget Timer0 is used for counting millis(), so you might just messed up some delay time

Code added :) it's working with the delay as you mentioned that timer0 is used for counting millis, but I'm working with true C coding. Is it still used for _delay_ms and _delay_us? Thank you,

You have been waiting 4 or 16 times as long to try to see any change, right?

No, _delay_*() are implemented with assembly code loops (which means that F_CPU must be set correctly).

I was waiting 4 or 16 times for what exactly ?

The main problem is the prescaler on Timer0 is already configured to divide clock source by 64 CS01 and CS00 are set (0b00000011).
And you are using bitwise OR to "change" prescaler: TCCR0B |= 0x05; or TCCR0B |= 0x04;. But this'll result into the clock source 7 (0b00000111) - clock source is expected on T0 input counting on rising edge.

WOW :) you absolutely right. The bitwise OR was the problem. OK so when to use the bitwise OR when I'm testing different codes and when not to use it? I use it with DDRs PORTs which works well, so here it did a problem !! Thank you very much for the help 3>


text:
How to detect Arduino serial port programmatically on different platforms?
I am trying to write a little program that needs to detect Arduino ports automatically. I have tried many methods but haven't found any reliable way.
I can see that the Arduino IDE can detect it, by showing /dev/cu.xyz (Arduino Uno) or COM6 (Arduino Uno) etc.
How could I detect if the device connected to the serial port is an Arduino or not? Preferably without pre-flashing the Arduino with specific firmware.
I found this Python version, which uses serial.tools.list_ports.comports() here,  but it didn't work when I tested it on Windows and MacOS.
The best I can get is by using go-serial's USBManufacturer, I can get 'Arduino (www.arduino.cc)'.
I also found this post, about the same question, but without any solution.

When I connect an Arduino Uno to my Linux box, lsusb says “ID 2341:0043 Arduino SA Uno R3 (CDC ACM)”. I don't know how to do that on other OSes though.

I agree with Edgar Bonet - if you can enumerate the USB ports you can work out which one has an Arduino on it, just like the IDE does.

Yeah, maybe usb info is all we can get since serial ports don't have any more info. The ports' Description and USBManufacturer could be used. Thank you guys.

A little more information about what you are trying to do would be helpful.

Quite late for the party! Just leave it here for anyone looking for a solution on windows.
The proper way is to read the device list from registry.
First location is

HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM

A better location is here

HKLM\SYSTEM\CurrentControlSet\Services\usbser\Enum

You have the list of Arduino devices there. Mine is Arduino Leonardo. Genuine Arduino UNO uses the similar chip and it should be in there as well.
To get the port, just copy the first device (index 0) and plug into this location

HKLM\SYSTEM\CurrentControlSet\Enum

So it is like this

HKLM\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_8036&MI_00\9&88cb209&0&0000

So you have friendly name and port number of the serial device. Then just write some code to read these registry locations.
In C
#include <windows.h>
#include <wchar.h>
#define MAX_VALUE_LENGTH 255

void getUSBSerialList()
{

    HKEY hKey;
    //check if we can read registry
    INT dwRegOPenKey = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum"), 0, KEY_READ, &hKey);
    if(dwRegOPenKey != ERROR_SUCCESS) return 0;

    DWORD type=REG_DWORD, size=0, USBser_count = 0; // a place for RegQueryValueEx to write back to
    DWORD dwRes;

    //read count of usb devices
    dwRes = RegQueryValueExW(hKey, _T("Count"), NULL, (LPDWORD) &type, (LPBYTE) &USBser_count, &size);
    if (dwRes) return 0;

    if (USBser_count)
    {
        for (INT i=0, dwRes = ERROR_SUCCESS; i<USBser_count; i++)
        {
            WCHAR achValue[MAX_VALUE_LENGTH];
            WCHAR buffer[MAX_VALUE_LENGTH];
            ZeroMemory(buffer, sizeof WCHAR  * MAX_VALUE_LENGTH);

            swprintf(achValue, L"%d",i); // read value name "0", "1"...
            dwRes = RegQueryValueExW(hKey, achValue, NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);

            // Plug that value into "SYSTEM\\CurrentControlSet\\Enum\\"
            HKEY hKey2;
            swprintf(achValue, L"SYSTEM\\CurrentControlSet\\Enum\\%s",buffer);

            INT dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
            if (dwRegOPenKey2) return 0; // check if this key exists

            // From here read friendly name
            dwRes = RegQueryValueExW(hKey2, _T("FriendlyName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
            if (dwRes) return 0;

            // or read COM port
            swprintf(achValue, L"%s\\Device Parameters", achValue);
            dwRegOPenKey2 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, achValue, 0, KEY_READ, &hKey2);
            if (dwRegOPenKey2) return 0;

            dwRes = RegQueryValueExW(hKey2, _T("PortName"), NULL, (LPDWORD) &type, (LPBYTE) &buffer, &size);
            if (dwRes) return 0;
        }
    }
}

In C#, just use Registry object to do so
int usbser_count = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\usbser\\Enum", "Count", -1);

I haven't done it in C# but I think it's easier than in C.
What if yours is arduino clone that use CH340 instead of atmega16u2, it won't appear in the registry location above. It will show up here instead:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum

You can do the same for other type of USB serial devices like CP210x (on some ESP32 dev boards)

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\silabser\Enum

Or even get a list of WinUSB devices (such as ST-Link v2)

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WINUSB\Enum

Here is a solution:
On Windows, Arduino IDE comes with a tool named listComPorts.exe, which will list all COM ports and their USB info like VID & PID. There is also a file named arduino.inf in drivers folder contains all known device types and their VID&PID etc, and we can look for the connected device.
On *nix, the IDE take advantage of libusb and no such a tool, and it's easy to find a tool to list usb info on these platforms.
This go package mentioned in the question is a good choice, which also uses libusb and could build on all platforms. (On windows, you have to install mingw to build the C code, cygwin & msys don't work, I tried TDM-GCC and it works. You also have to add LDFLAGS: -lsetupapi (in serial.go) to successfully link the code.) After list all serial ports, you can search for 'Arduino' to determine the port. 'CH340' is also a keyword to search as many modified boards use this chipset.
New version of the IDE don't have listComPorts.exe, they all uses libusb. I find this tool from version 1.6.5.

You can start the Arduino IDE wait unit the port is detected-which are stored on the hard drive by the arduino IDE;exit the IDE; then read through that file with your custom Windows (or whatever OS you're using -to get your answer. This answers your question you wrote above.

This is not applicable as the program is to run on machines without Arduino IDE, and the detecting process should be AUTOMATICALLY.

That wasnt clear to me from your question -which is why I wrote "This answers your question you wrote above."

The arduino IDE is open source so you can get the part of the code that does that COM detection-this will require some work on your part-and use it in your own program

So as far as I can understand that does answer your question

OK, I am trying to find the related part from the source code. Thank you anyway.

Here is snippet of C# code based on answer by SimonVu14. It looks through the named keys and gets ports for both Atmega and CH340 chips. If you expect to have just one Arduino connected to the computer, you can just go with the first one found. Otherwise you'll need to invent something to figure out which one is yours (which usually involves opening port, sending some predefined request and expecting some predefined response), or give user option to select via UI.

    private readonly string[] _arduinoKeys = {
        @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\usbser\Enum",
        @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CH341SER_A64\Enum"
    };

    /// <summary>
    /// See https://arduino.stackexchange.com/questions/30808/how-to-detect-arduino-serial-port-programmatically-on-different-platforms/80887
    /// </summary>
    private IEnumerable<(string name, string port)> EnumerateArduinos()
    {
        foreach (var arduinoKey in _arduinoKeys)
        {
            var countObject  = Registry.GetValue(arduinoKey, "Count", null);
            if (countObject is not int count)
            {
                continue;
            }

            for (int i = 0; i < count; i++)
            {
                var enumObject = Registry.GetValue(arduinoKey, i.ToString(), null);
                if (enumObject is not string enumKey)
                {
                    continue;
                }

                var friendlyName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}", "FriendlyName", null);
                var portName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\{enumKey}\Device Parameters", "PortName", null);
                if (portName is string port && friendlyName is string name)
                {
                    yield return (name, port);
                }
            }
        }
    }


text:
Amplify Piezo Sensor
I am trying to amplify a piezo sensor per the instructions found at the link below.  I am not trying to trigger a buzzer only print to the serial monitor whether the vibration was detected or not.  I am a NOOB with respect to circuits and unable to understand why my circuit is not working.
The piezo is either giving a positive (sensing) reading or  giving a negative (not sensing) reading depending on where the poteniometer is set.  There is no state where-if all is quiet-the piezo is quite and if there is a vibration the piezo senses it and reports to the serial monitor.
I see from the blog that if the piezo get stuck on a state to lower the feedback resistor of the op-amp from 220k to 160k but again, there is never a case where it is working then get struck in state.  It is always stuck in a state!
The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor.  I am using the 10uf capacitor.  Will switching out the 10uf for a 0.1uf capacitor test potentially damage the Arduino? Is this the cause of the +-state of the piezo? Do I just have a wiring flaw?
Any advice is appreciated.
Here is a link to the post including the Fritzing diagram.
http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html
Here is a picture of my circuit.

And the Sketch...
#define VIBRATION_DIGITAL_IN_PIN 8
int DurationMillis = 1000;

void setup()
{
  Serial.begin(9600);
  pinMode(VIBRATION_DIGITAL_IN_PIN,INPUT);
}
void loop()
{
  if(digitalRead(VIBRATION_DIGITAL_IN_PIN)==HIGH)
  {
    Serial.println("I felt that");
    delay(DurationMillis);
  }
  else
  {
  Serial.println("I don't feel anything...");
  delay(DurationMillis);
  }
}

You write,

The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the high-sensitivity-vibration-sensor at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard.  This is a reasonable thing to do, to avoid power supply glitching on that board.  It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.
The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input.  This will block any DC voltage coming out of the piezo from going into the op amp input.  It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there.  A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies.  The presence or absence of that capacitor probably isn't the problem with your circuit.  Looking at your circuit photo, the wiring looks ok[*].  Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working.  If they aren't working, substitute for the LM358.
[*] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1.  Also is your comparator output connected into digital pin 8 on the Uno?  It looks more like 9 or 10 in the photo.  Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.

jwpat7, Thanks so much for your advice.  I was able to confirm that the piezo element was working by using the Knock sketch that is included in the Arduino IDE.  I finally received a  new LM358 dual-op amp (from the slow boat from China).  Using the new LM358 chip solved the problem.  My piezo amplifier is working!


text:
How to send multiple data from PC to arduino
I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication.
 I have two variables:
//Code in arduino
int ADelay = 1000;
int BDelay = 1000;

I want to change the value of each variable based on the input of the user using the java interface.
Is there a code that let the arduino identify that this data:
2000

Is intended to or for:
int ADelay

and this
300

is for
int BDelay

My only idea on how to achieve this is to add A or B before the number before i send to arduino
A2000
B300

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks

And how has that failed you?

I want to know if my idea is right or is there other simple way to do it :D

how often do you need to poll the data?

It depends , but maybe twice is the maximum .

The approach noted in the question – having an identifying character at the front of each number – is a workable approach.  Other approaches include:
•  always sending numbers in pairs, eg 2000,300 would denote A2000 B300.
•  encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
•  sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.
One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front.  This allows your code to pick up digits until a letter appears, and then dispatch based on the letter.  Here's some example code:
// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow.      - jiw 3 Nov 2016

void setup() {
  Serial.begin(115200);         // init serial port
}

unsigned int val=0;
void loop() {
  char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
        break;
      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }
  }
}

Edit 2: This edit incorporates some code suggestions from comments into the answer.

If you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:
...
case ',':
  val1=val; v1flag=1;
  break;
...
case 'B':
  if (!v1flag) val1=val1default;
  Serial.print("B stuff with val and val1");
  v1flag=0;
  break;
...

To retain when the power is off, you can write a recordData() function, that when called will write selected data to EEPROM if the value has changed.  In setup(), load data from where you stored it. For data validation, you can store in the cell after a value v its complement, ~v.  If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:
case a :
  WATEREQFORN1 = val;
  EEPROM.put(0, WATEREQFORN1);
case b :
  WATEREQFORN2 = val;
  EEPROM.put(1, WATEREQFORN2);
case d :
  DELAY = val;
  EEPROM.put(3, DELAY);

Logic or syntax problem: Missing break statements at  ends of cases.  This error will allow execution to flow from one case into the next.  While there are situations where that's useful, this is not one.
Logic or syntax problem: Unless a, b, ... are declared constants they won't work as case designators.  Perhaps use 'A', 'B', ... instead.
Style problem:  Variable names in all upper case.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of WATEREQFORN1 consider waterEq1.
Allocation problem:  Presumably the WATEREQ... variables are multiple bytes in length.  EEPROM.get() and put() read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if WATEREQFORN1 is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.
The following code snippet fixes some of those problems.
enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...

Can you give me a code snippet C programing  language on how to pick up digits until a letter appears and make an if else condition based on the letter :D Thanks a lot

@kaisarGreat, see edit for working example

Thank You Sir :D for your help and time :) @jwpat7 it really help me :D

Sir @jwpat7 is it posible to combine the snippet code above you give and one approach you give the sending numbers in pair ? Example I will send 200A300 or 200,300A then put them in separate varables .. 200B300 or 200,300B ..

Yes, you can do that, but handling numbers in pairs complicates the parsing  – it's simpler and easier to handle independent values.  ¶ That said, one approach is to add  case ',': val1=val; break; into the switch, and then when you get the A or B (for a form like 200,300A or 200,300B) do an action using both val1 and val.  That is, the action for the comma case stores a value for future use; while letter cases can use two vals.

I did what you told sir @jwapat7 , I add 'case ',': val1=val; break' then in the both 'case 'a'' and 'b' I add 'Serial.println(val1);' and It works like a charm :) Thanks for your quick reply .

Also, if you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:  case ',': val1=val; v1flag=1; break; .... case 'B':  if (!v1flag) val1=val1default; Serial.print("B stuff with val and val1");  v1flag=0; break;

@kaisarGreat, please feel free to upvote answer

Sir @jwpat7 I want to upvote your answer but my reputation  is less 15 :D Thanks for the additional Information.

Sir is it possible to save the value send example 200,400A .. then spilt 200 to val1 and 400 to val2 and save them into different variables but remains when the power of arduino is put out .

@kaisarGreat, you could write a recordData() function, that when called will write indicated data to EEPROM if the value has changed.  In setup(), load data from where you stored it.  For data validation, you can store in cell after a value v its complement, ~v; if you load data and it fails the validation test, then write a default value to EEPROM.

I used the above code you give and add some inside the case here is for case a : WATEREQFORN1 = val;            EEPROM.put(0, WATEREQFORN1); case b : WATEREQFORN2 = val;            EEPROM.put(1, WATEREQFORN2); case d : DELAY = val;            EEPROM.put(3, DELAY);   but when i change the value of A , then change the value of B the value on A will also change in random numbers .. how could i achieve writing into eeprom without changing some that i already save in there ..

If you are just looking to send something as simple as 2 integers, your approach should be fine, you just need to set your own protocol to encode the data from java and decode it on the arduino side.
Another easy way would be to set a starting byte, could be anything like 0x6A etc, (with optional checksum if it's through bluetooth or other noisy communication method):
[8 bit starting byte][32 bit integer data A][32 bit integer data B]

On the arduino side you want to keep polling for the starting byte, once you receive the special byte then the next 32 bits would be your data A and the following 32 bits would be your data B.
However if you want something more robust or object oriented you could look into this library:
https://github.com/bblanchon/ArduinoJson
It allows you to decode and encode JSON objects which is very flexible and widely accepted, so you just need to encode the data into a JSON object on the java side and decode it using that library.