text:
Arduino MEGA crashes with Ethernet shield to connect to two TCP servers
I have Arduino MEGA with Ethernet Shield and a SD card connected to a RUT950 GSM router. Then, I also have two sensors connected to the router and they run a TCP server that sends measurements character after character with a "\n" to terminate the measurement.
I got this from the uSonic Wind Sensor:
    $WIMWV,000.0,R,00.0,M,A*10\n
    $WIMTA,022.8,C*23\n
    $WIMHU,083.3,,019.8,C*05\n
    $WIMMB,,,1006.8,B*0F\n

Sensor 1, local IP: 192.168.1.200, port 1649
Sensor 2, local IP: 192.168.1.201, port 1647
Router: 192.168.10.1
Arduino: 192.168.10.100
My program reads from the two TCP servers, store the readings in a char buf[] and then it saves them into a SD card. Then, the program load the file and sends it to the FTP server.
This works fine sometimes, other times it crashes or it starts receiving the data from the two sensors but after some minute, it appears to received only from one sensors or it receives nothing at all. It is very strange! Sometimes, it sends the file only the first time and so on. It has a really random behaviour and I cannot understand why!
Can you help me please?
The sensors have only a public ip address so you can try the code on your pc, if you want to (I can give you the public ip address).
// Library includes
#include <SD.h>
#include <FTP.h>
#include <RTC.h>
#include <Ethernet.h>

// Set Ethernet properties of our PLC
uint8_t mac[] = { 0xDE, 0xAD, 0x4E, 0x55, 0xFE, 0xED };
IPAddress ip(192, 168, 10, 100);
IPAddress netmask(255, 255, 255, 0);
IPAddress server(2, 45, 150, 21);

byte server_svs60[] = { 192, 168, 10, 201 };  // Touchberry Pi Server
int tcp_port_svs60 = 4197;
byte server_wind[] = { 192, 168, 10, 200 };  // Touchberry Pi Server
int tcp_port_wind = 4196;
EthernetClient client_svs60;
EthernetClient client_wind;

const byte numChars = 32 * 4;
char receivedChars[numChars + 1];
char tempChars[numChars + 1];  // temporary array for use when parsing

const byte numChars_wind = 32 * 4;
char receivedChars_wind[numChars + 1];
char tempChars_wind[numChars + 1];  // temporary array for use when parsing

byte lineCount = 0;

IPAddress time_server(147, 156, 7, 26);  // es.ntp.pool.org
unsigned int udpPort = 2390;
EthernetUDP udp;
const int NTP_PACKET_SIZE = 48;      // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[NTP_PACKET_SIZE];  //buffer to hold incoming and outgoing packets

// Variable to save the hour and second
int savedHour;
int savedSecond;
char datetime[50];
// Variables to manage the SD card
Sd2Card card;
SdVolume volume;

bool flag_wind = false;
bool flag_svs60 = false;

// Define the variables for FTP management
EthernetClient ftpControl;
EthernetClient ftpData;
FTP ftp(ftpControl, ftpData);

// Setup function
void setup() {
  // Set the speed of the serial port
  Serial.begin(9600);

  // Init the SD Card
  if (!SD.begin(53)) {
    Serial.println("Card failed, or not present");
    while (true)
      ;
  }

  // Configure the ethernet protocol in our PLC
  Ethernet.begin(mac, ip, netmask);
  Serial.print("IP address: ");
  Serial.println(Ethernet.localIP());

  if (client_svs60.connect(server_svs60, tcp_port_svs60)) {
    Serial.println("Connected to the SVS60 server");
    client_svs60.println();
  } else {
    Serial.println("Connection to the SVS60 TCP Server failed");
  }
  delay(1000);

  if (client_wind.connect(server_wind, tcp_port_wind)) {
    Serial.println("Connected to the Wind server");
    client_wind.println();
  } else {
    Serial.println("Connection to the Wind Server failed");
  }

  int c = ftp.connect("2.45.150.21", "geoatlas", "Datiboa2023@");
  while (!c) {
    delay(1000);
    c = ftp.connect("2.45.150.21", "geoatlas", "Datiboa2023@");
  }

  udp.begin(udpPort);
  sendRequest();
}

// Loop function
void loop() {
  Serial.println("parsePacket");
  if (udp.parsePacket()) {

    udp.read(packetBuffer, NTP_PACKET_SIZE);

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    const unsigned long seventyYears = 2208988800UL;
    unsigned long epoch = secsSince1900 - seventyYears;

    RTC.setTime(epoch);
    RTC.write();
  }
  Serial.println("rtc read");
  if (!RTC.read()) {
    Serial.println("Read date error: is time set?");
  } else {
    //filename_sd = String(RTC.getYear() + String("") + RTC.getMonth() + String("") + RTC.getMonthDay() + String(".txt"));

    sprintf(datetime, "%04d-%02d-%02d %02d:%02d:%02d",
            RTC.getYear(), RTC.getMonth(), RTC.getMonthDay(),
            RTC.getHour(), RTC.getMinute(), RTC.getSecond());
  }
  // Serial.println(datetime);
  Serial.println("svs60");
  if (client_svs60.available()) {
    Serial.println("dentro svs60 sensor");
    char c = client_svs60.read();
    Serial.println(c);
    strncat(tempChars, &c, 1);
    if (c == '\n') {
      strcpy(receivedChars, tempChars);
      strcpy(tempChars, "");
      Serial.println("I got this from SVS60: ");
      Serial.println(receivedChars);
      logToSd_svs60(receivedChars);
      sendToFTP();
     // memset(0, receivedChars, sizeof(receivedChars));
    }
  }
 Serial.println("wind sensor");
  if (client_wind.available()) {
    Serial.println("dentro wind sensor");
    char c1 = client_wind.read();
    Serial.println(c1);
    strncat(tempChars_wind, &c1, 1);

    if (c1 == '\n') {
      if (++lineCount == 4) {
        strcpy(receivedChars_wind, tempChars_wind);
        strcpy(tempChars_wind, "");
        lineCount = 0;
        Serial.println("I got this from the uSonic Wind Sensor: ");
        Serial.println(receivedChars_wind);
        logToSd_wind(receivedChars_wind);
       // memset(0, receivedChars_wind, sizeof(receivedChars_wind));
      }
    }
  }

  delay(200);
}

// Function to save information to SD
void logToSd_svs60(char value[]) {
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    Serial.println("Saving SVS60 to SD");
    dataFile.println("Sensore Ondametrico: ");
    dataFile.println(datetime);
    dataFile.println(value);
    dataFile.close();
  } else {
    Serial.println("Error opening datalog.txt");
    while (true)
      ;
  }
}

// Function to save information to SD
void logToSd_wind(char value[]) {
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    Serial.println("Saving Wind to SD");
    dataFile.println("Dati sistema: ");
    dataFile.println(datetime);
    dataFile.println(value);
    dataFile.close();
  } else {
    Serial.println("Error opening datalog.txt");
    while (true)
      ;
  }
}

unsigned long sendRequest() {
  memset(packetBuffer, 0, NTP_PACKET_SIZE);

  packetBuffer[0] = 0b11100011;  // LI, Version, Mode
  packetBuffer[1] = 0;           // Stratum, or type of clock
  packetBuffer[2] = 6;           // Polling Interval
  packetBuffer[3] = 0xEC;        // Peer Clock Precision
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;

  //Serial.println("I check the time server");

  if (!udp.beginPacket(time_server, 123)) {
    Serial.println("Begin packet error");
  } else {
    udp.write(packetBuffer, NTP_PACKET_SIZE);
    if (!udp.endPacket()) {
      Serial.println("End packet error");
    }
  }
}

void sendToFTP(void)
{
  Serial.println("SD.open");
  // Open the SD file
  File dataFile = SD.open("datalog.txt");

  // Check if the file was succesfully open
  if (dataFile)
  {
        Serial.println("Sending trough FTP connection");
        ftp.store("datalog.txt", dataFile);
        dataFile.close();

  }
  else
  {
        Serial.println("Error opening2 datalog.txt");
        while (true)
          ;
  }
}

did you try some recovery like reconnect when connected() returns false?

But the problem is that I'm not sure the problem is related to a loss of connection. Moreover, I call the client.connect() inside the setup() so I do not know if I can check it inside the loop function. Should I check if client is connected inside the loop function just before client.available? But in this way, should I change also the control of the received characters?

I do not know if I can check it inside the loop function. ... examine the example code that is included with the ethernet library ... ask questions after

Probably I solved the system by checking if the client is connected and also by re-connecting it at some time interval.


text:
Using Arduino to pass data from a coin collector to android app
Okay. Basically I want the android app to be able to recognize that a coin was inserted into the coin collector before it allows the user to use certain functions of the app.
However I am unsure what would be the best way to pass the data from the coin collector to the Android app.  My currently train of thought is to have the coin collector connect to an Arduino board which would then connect to the android app and send the input through that connection.
I was wondering if anyone knows of a better way to achieve this, or whether this is an acceptable/standard solution.
Thank you in advance!

This is unanswerable without details of the Android hardware and security model on which the app will run.

The interface to the coin collector highly depends on the coin collector you use! The interface to the Android app highly depends on the Arduino environment you use; Bluetooth would be a reasonable approach. BTW, to me the idea of using high end electronics which requires old-fashioned coins to work sounds a little bit odd ;-)

Here are a couple of opitions for you:
1- Bluetooth - if in close range, an HC-05 will work great.
2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.
3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.
All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.

source: Stack Exchange

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

sort: votes


text:
How to repair or work around a damaged usb port on the Arduino?
While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

How would you go about repairing this?
If I fail to repair it is there an alternate method to programming the board?

I was able to use a paperclip to carefully bend it back and put the plastic divider back in. I will just have to leave the cable plugged in from now on.

I would suggest to actually remove the whole thing and resolder it. There are many tutorials out there is you're new to soldering. This way, it is less probable that it creates a short or data loss during compilation.
If you don't want to solder, then you might be able to use an FTDI connector. FT232s are quite cheap.
Tx > Rx
Rx > Tx
Reset > Reset
Vcc > Vcc
GND > GND

You would need to replace the whole socket in order to repair it. For that you would need:

Soldering iron
Solder sucker
Solder wick
Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.

Also connect Vcc and GND of course.

That would (I hope) go without saying, although if the Arduino is separately powered the power connection is not needed, only ground.

You could try bending the pin back, removing the white part from your cable, and gluing it back in.
Second option is to replace the USB socket on the Arduino board. You might be able to salvage a socket from some old electronics you still have lying around.
Third option is to cut one end of a spare USB cable, and solder the 4 wires inside the cable directly to the corresponding pads on the bottom of the broken socket. Add some glue to provide some strain-relieve to the cable.
Fourth option is an external USB to serial converter, like @Majenko suggested.

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


text:
Replacing several pinMode() and digitalWrite() pins with an array
I'd like to 'clean up' some code that involves several pinMode() and digitalWrite() lines by using a single line of an array. I'm very new to both arrays so I'm a bit confused. The following examples are sections from code that controls a 4 digit, 7 segment LED.
// Define display pins
// Digit pins (common cathode)
int digit1 = 13; //Display pin 1
int digit2 = 12; //Display pin 2
int digit3 = 11; //Display pin 6
int digit4 = 10; //Display pin 8
// Segment pins
int segA = 2; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = 6; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);

  pinMode(digit1, OUTPUT);
  pinMode(digit2, OUTPUT);
  pinMode(digit3, OUTPUT);
  pinMode(digit4, OUTPUT);
}

#define SEGMENT_ON  LOW
#define SEGMENT_OFF HIGH

  switch (numberToDisplay){

  case 0:
    digitalWrite(segA, SEGMENT_ON);
    digitalWrite(segB, SEGMENT_ON);
    digitalWrite(segC, SEGMENT_ON);
    digitalWrite(segD, SEGMENT_ON);
    digitalWrite(segE, SEGMENT_ON);
    digitalWrite(segF, SEGMENT_ON);
    digitalWrite(segG, SEGMENT_OFF);
    break;

Defining pins:
I'm pretty sure the code below is the correct way to store the pins as an array (but please correct me  if I'm wrong).
digitPins[] = {13 12 11 10};
segPins[] = {2 3 4 5 6 7 8};

pinMode():
I understand I could use a for loop to set the pin modes but is there an even simpler way? Would something like this work?
pinMode(digitPins[], OUTPUT);
pinMode(segPins[], OUTPUT);

digitalWrite():
I could access the appropriate pin from the array to use in digitalWrite() like the code below but that would result in the same number of lines of code (and be even more confusing). Is there another option?
digitalWrite(segPins[1], HIGH);

Some relevant questions: Interfacing key-pad with arduino with 7 segment display and 7-segment display code.

Since this is about a 4 digit, 7 segment display, the most relevant question to check is probably: How to use a common anode 7-segment, 4-digit display?.

the correct way to store the pins as an array

Your array initializers are almost right; you just need to separate the values with commas:
digitPins[] = {13, 12, 11, 10};
segPins[] = {2, 3, 4, 5, 6, 7, 8};

You will need to call pinMode() in a loop; it doesn't accept arrays as arguments.

How about for digitalWrite() where its a mix of HIGH and LOW?

There are (at least) two ways: Make arrays of HIGH and LOW values, matching the digitPins[] and segPins[] arrays one-for-one, respectively. Or for easier maintenance, declare a data structure (struct) of a pin # and a value; make an array of those. It's a bit more complex but also more useful. So, for example:
typedef struct {
    uint8_t pinNum;
    bool pinVal;
} pinInit_t;

pinInit_t digitPins[] {
    {13, HIGH},
    {12, LOW},
    {11, LOW},
    {10, HIGH}
};

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

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

struct is short for "data structure"; it lets you combine data of different types into a single named and addressable unit. typedef declares a new data type, and says "Don't allocate any memory just now; this (pinInit) is just a description. I'll use it later on." It makes pinInit a named data type, usable wherever you can use a native data type AND a multi-valued data type (such as an array) is permissible.
Thus, we can make an array of pinInits (pin-# / boolean-value pairs) just by using the name of the new type.
Then your initializing code might look like:
uint8_t i;
for( i = 0; i < sizeof(digitPins)/sizeof(pinInit_t); ++i ){
   pinMode(digitPins[i].pinNum, OUTPUT);
   digitalWrite(digitPins[i].pinNum, digitPins[i].pinVal);
}

The expression sizeof(digitPins)/sizeof(pinInit) evaluates to the number of initializers (# of bytes in the array / # of bytes in one array member).
The expression digitPins[i].pinNum means: "in the pinInit array digitPins, get the i-th element..." (remember, this is a pair of values), "... and take value of the member "pinNum". A little more complex, the first time we think about it, but look at how easily the array reads. And a hint about reading that expression: I read it backwards: "the pinNum member of the i-th element of the digitPins array."
Tomorrow, or next month, when we need another pin, no need to update 2 arrays (remembering of course, to keep them in sequence with each other!); just add another 2-valued element to the one digitPins[] array.

[ADDITIONNAL CODE and EXPLANATION OF THE CODE]
This is the function that is used in the link posted in the comments:
void number(int num)                        //num is the number to display
{
  for(int i=0; i<7; i++)                    //going through the 7-segments (7 leds)
  {
    digitalWrite(segment[i], nums[num][i]); //tell the arduino to turn on or off which led
  }
}

It is great because you can use it by calling:
number(/*the number you want to display*/);

Using a for loop will avoid copying and pasting a buch of things. It also permits you do save a lot of memory.
Then, to display a small 0-9 timer, you can do this:
for(int i=0; i<10; i++)
{
  number(i);            //display the number
  delay(1000);          //wait 1sec
}

[ORIGINAL ANWSER]
Use an array and a for loop.
int segments = {2,3,4,5,6,7,8}; //declaring the pins

void setup() {
  for(int i=0;i<8;i++)
  {
    pinMode(segments[i], OUTPUT); //declaring them as outputs
  }
}

It's very useful. Do the same for the digits too.
This method works in many cases:

many sensors, switches
many outputs such as leds, relays, transistors

How about for digitalWrite() where its a mix of HIGH and LOW?

@zdub that will indeed make things more complicated, but if you want a good solution to what you are likely looking for, you should edit your question to show more than one possibility for the data to be written.

here is a post I posted quite a while ago about 7-seg: http://arduino.stackexchange.com/questions/30031/switching-methods-functions-with-a-button/30032#30032

For a mix of HIGH and LOW just have the list of HIGH and LOW in an array as well. By the way, be sure to make the array const and, even better, arrange it in PROGMEM as well, though that has performance implications.

@canadiancyborg 2D arrays!! Didn't know this was an option but I think it will work. Why does this digitalWrite(segment[i], nums[num][i]) have to be in a for loop? Why cant 'i' just be a variable and the code works without the for loop.

well because you have 7 segments per led and how many digits to turn on??? an array is simply faster. Ill edit the anwser in a min. and ill explain the code a little further

forget what i just said in the previous comment, just follow the edit of the anwser!!!

Custom method usage
Used reference: https://stackoverflow.com/a/33235154/5500092
You can use a custom method like this:
template<size_t size>
void pinMode(const uint8_t (&pin)[size], uint8_t mode) {
    for (size_t i = 0; i < size; ++i) {
        pinMode(pin[i], mode);
    }
}

template<size_t size>
void digitalWrite(const uint8_t (&pin)[size], uint8_t val) {
    for (size_t i = 0; i < size; ++i) {
        digitalWrite(pin[i], val);
    }
}

Then you define an array with the pins:
uint8_t displayPins[4] = {13, 12, 11, 10};
uint8_t segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};

And finally in your setup use:
void setup() {
    pinMode(displayPins, OUTPUT);
    pinMode(segmentPins, OUTPUT);
}

void loop() {
    // Your logic with digitalWrite.
}

Your logic
PS: For your logic, you can even use:
template<size_t size>
void digitalWrite(const uint8_t (&pin)[size], const uint8_t (&val)[size]) {
    for (size_t i = 0; i < size; ++i) {
        digitalWrite(pin[i], val[i]);
    }
}

And define for each segment number a custom value array.
uint8_t zero[7] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
...

Or even:
uint8_t segment[][7] = {{HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW }, // 0
                        {____, ____, ____, ____, ____, ____, ____}, // 1
                        {____, ____, ____, ____, ____, ____, ____}, // 2
                        ...
                        {____, ____, ____, ____, ____, ____, ____}}; // F

And use:
digitalWrite(segmentPins, segment[5]); // print 5

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


text:
print data after being plugged back into USB
I have an arduino uno powered by a battery on a buggy with a sonar distance sensor.  I have a program that calculates the speed it's going, and I want to correlate speed with stopping distance.  I can measure the stopping distance manually, but I want the arduino to report to me the speed it was going when the motor was turned off.  I don't have an LCD display - I wanted to print the number to the serial monitor, but plugging it back into the USB port resets everything I think, or at least the serial monitor.
Without buying more components, can I get the data (calculated speed) somehow?

There are ways of disabling the auto-reset feature: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see:
http://www.arduino.cc/en/Reference/EEPROM


text:
ESP-12f SoftwareSerial read fails
I am trying to use esp8266 version of SoftwareSerial,  espsoftwareserial, on an esp-12f.
If I initialize an object using:
SoftwareSerial gpsSer(14,12, false, 256);

or
SoftwareSerial gpsSer(12,14, false, 256)

then gpsSer.write works in all both cases, using ports 12 and 14 for transmit appropriately,  but gps.read fails.
I would be grateful for any advice.
Paul

have you tried to use it with another serial device? You can even try to link it  to the hardware RX TX of esp to see if it behaves as expected.

Impossible to answer without seeing the full code.

The sketch works fine if i use the hardware TX, RX I only use the RX port from the ESP to read the output of a GPS device which produces about 200 bytes per second


text:
Expected declaration before } token
Below is my code. The idea is it is supposed to wait for the ? character, print K, and turn on the LED. If it does not detect ? then it should keep waiting.
Below is my code:
incomingByte = Serial.read();
sendBack = K;
int pollTime = 200;

int ledPin = 9;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
while(Serial.available())  {
  if(Serial.read == '?')  {
  Serial.print(sendBack);
  pinMode(9,OUTPUT);
  else  {
   delayMicroseconds(pollTime);
  }
}
}
}

why do you declare 9 as an output in the void loop???

Try this:
void setup() {
  Serial.begin(9600); //set baud rate.
  pinMode(9, OUTPUT);
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == '?') {
      Serial.println("OK");
      digitalWrite(9, HIGH);
      delay(1000);
    }
  }
  else
  {
    digitalWrite(9, LOW);
  }
}


text:
Expected } at the end of input
I am getting the error in my title when I try to compile the following code:
#define char incomingByte; //Defines incomingByte
#define char sendBack = K;
#define char ?;
#define pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.
incomingByte  = Serial.read();
if(incomingByte = ?) {
Serial.print(sendBack);
  }
 }
}

Your code is completely wrong in almost every respect.

#define char incomingByte; //Defines incomingByte

That line means that the compiler will substitute incomingByte; whenever it sees char.

#define char sendBack = K;

Now it will substitute sendBack = K; when it sees char.

#define char ?;

Now it will substitute ?; when it sees char.

#define pollTime;

I don't know what you are thinking here. If you are trying to declare a variable you have to give a type, like this:
int pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

Those lines are OK.

for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

You don't want the semicolon there. A for loop is not written like that. You possibly mean while, ie.
while(Serial.available() > 0)

pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

That is doing nothing of the sort. It is delaying 200 µs, it isn't setting anything.

incomingByte  = Serial.read();

That line is OK, assuming you declared incomingByte like this, and not the way you did:
char incomingByte;

if(incomingByte = ?) {

That needs to be in single quotes, as you are comparing a character. Also you compare with == not = ie.
if(incomingByte == '?') {

Serial.print(sendBack);

It looks from your earlier code you mean:
Serial.print('K');

  }
 }
}

These lines look OK.

I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how #define works. Here is one page: https://www.techonthenet.com/c_language/constants/create_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html

Thank you. This was very helpful. I'll look into the links that you provided.

P.S. you should change "respect" to "aspect" in the first line

I'm not sure about that. See in all respects which means: entirely, outright, wholly, thoroughly, altogether, totally, utterly

[UPDATE]
Try this:
int question = 63; //in the ascii table, ? is 63

void setup() {
  Serial.begin(9600); //set baud rate.
}

void loop() {
  if (Serial.available())  { //Gets you the number of bytes that are available to be read from the serial port.
    if (Serial.read() == question) {
      Serial.println("OK");
    }
  }
}

When I run the code it gives the following error:

invalid conversion from 'const char*' to 'char' [-fpermissive]

refresh the page and test the new code

Thank you. This part worked. I forgot to mention that I also need it to turn off the LED if the condition is not met. When I run the code you have provided the LED is on.

There's really no reason to use the ascii code for a question mark here, it makes the program hard to understand.  Use '?'your earlier error was a result of using a string (double quotes) rather than a single character (single quotes).

"When I run the code you have provided the LED is on" - your question was nothing to do with LEDs, nor does your code make any attempt to turn them on or off.


text:
Formula for current through shift register

Hi
I am programmer that just started learning electronics and Arduino. I built this simple circuit on Autodesk Circuits earlier. Originally I used 220 ohm resistors. Then when I ran the simulation and turned on more than 4 of the leds the simulator warned that I exceeded the max current for the shift register.
I then upgraded to 560 ohm resistors which solved the problem.
What I would like to know is how can I calculate the current through the shift register for each n-number of leds I turn on? That way I can calculate the right resistor that I need before I burn out my electronics.
Thanks for the help on this.

Datasheet says?

It's just N×IL+IQ where N is the number of LEDs, IL is the current through each LED and IQ is the current the shift register needs to operate (quiescent current).
The current through each LED is just (VIN - VLED) ÷ R, where VIN is 5V, VLED is the forward voltage drop of the LED, and R is the value of your resistor.
So you can combine it to be a single formula, if all your LEDs are the same and your resistors are the same, to:
IT = N × ((VIN - VLED) ÷ R) + IQ

There's a voltage drop across the shift register, too, but that may not be worth worrying about.  VLED may be most simply measured in operation - or else, calculating based on VLED=0 would somewhat overestimate the current, which isn't really a bad thing to do when comparing against a limit, since it just builds in some margin.  But if the LED were blue with a high forward voltage, then VLED would be very large - if the supply were only 3.3v  it would actually be the majority of the voltage drop.

Of course, the correct thing to do is throw away the poxy shift register and use a proper LED driver with constant current sink... Many are identical in operation from a programming and interfacing perspective, and remove the need for all the resistors completely.

Thanks. I looked through the data sheet. Can find Iq only Icc and Io for each pin. I also have no idea what the specs are for the leds the simulator does not provide specs. I will just make sure I know the specs before I put together a real circuit.

Sorry meant I can't find Iq.

@HeinrichKruger 80µA


text:
Reading from software serial with an interrupt
I want to perform a serial read using software serial with Arduino. I am looping for my normal tasks, but whenever something is received on the software serial pins I want to perform a read operation and based on the character received, I want to run a function in the loop.
I think this is possible with interrupts only. But I can not see any documentation or help on how to perform this.
How to write an ISR for this task?

Please explain why you want to do such a thing. What is the difference of writing the incoming data in a buffer and processing that buffer in the loop. I think that if you write you sketch with 'millis' instead of 'delay' and use a hardware serial port with the standard Arduino functions, then all your problems are probably solved. Could this be a XY-problem ( http://xyproblem.info/ ) and your real question is how to reduce latency for incoming serial data in your sketch ?

you actually want more of an event callback than a strict interrupt routine

You can't do it directly with an interrupt. SoftwareSerial already uses an interrupt to do the actual reception - the received byte being placed in a circular buffer.
The only thing you could do would be to modify the source code for SoftwareSerial so that instead of storing the byte in the buffer it calls your custom code instead.

Ok, so you're NOT using SoftwareSerial, you're using (something which I have never heard of) "NeoSWSerial". That has the ability to attach an interrupt (by adding it to the reception interrupt ISR), and the README.md file with that library gives you an example of how to use it:
#include <NeoSWSerial.h>
NeoSWSerial ss( 4, 3 );

volatile uint32_t newlines = 0UL;

static void handleRxChar( uint8_t c )
{
  if (c == '\n')
    newlines++;
}

void setup()
{
  ss.attachInterrupt( handleRxChar );
  ss.begin( 9600 );
}

So just read the character in there, set a flag to say you have a new "mode" arrived, and in your loop react to that flag and run the right function for that mode.
If you want to terminate a mode early you will have to program your modes to also react to the "new mode" flag and terminate. The interrupt cannot do that for you.

can I do something with attachInterrupt?

No, you can't do anything with attachInterrupt.

I am using NeoSWSerial not the original Software Serial it has attachinerrupt function   https://github.com/SlashDevin/NeoSWSerial/blob/master/src/NeoSWSerial.cpp

Well that's a completely different story. It would have helped if you had stated that in your question. When you say you are using software serial it's immediately assumed (unless explicitly stated otherwise) that you are using the standard Arduino software serial. If you aren't you must state that at the beginning. Then we can tell you to go and read the manual where it shows you exactly how to do what you want to do.

Is some help possible with that library. Sorry, I thought NeoSWSerial is like an extension of the original one so I thought may be the library already has some support. Please help if possible

You mean the example, which I have copied and pasted for your convenience, is not enough? Do you want me to type it in for you as well?


text:
ATTiny 85 analog input pin number problem
I am using AT Tiny 85 to read voltage from lead acid battery charger while charging.  Basically the setup has two 7-segment displays driven by two SIPO shift registers(74ls164n). And used tiny 85's pin 4 (physical pin3) to read voltage.
I tested the code using arduino and finally burned it to AT Tiny 85,   it didn't worked, i debugged it for hours, and pulled hair out of my head, tested it on bread board, eventually i changed the port to "A2" from "4" and surprisingly, everything runs as expected.
My question is why this happens? why analogRead(A2) works while analogRead(4) don't. ?
I am using Arduino IDE 1.6.5 with https://github.com/damellis/attiny  (1.0.1 installed from the board manager) .

Full Code:
//// Arduino Uno Pins
//const int data = 8 ; //Tiny pin 3 (Physical 2)
//const int clock = 9 ;//Tiny pin 2 (physical 7)
//const int battery_Sensor = A0; //Tiny pin 4 (physical 3)
//const int charger_ctrl = 5;   //Tinypin 1 (physical 6)

// ATTiny 85 Pins
const int data = 3 ;
const int clock = 2 ;
const int battery_Sensor = 4;
const int charger_ctrl = 1;

int outputValue = 0;
int sensorValue = 0;
int voltage_reading = 0;
int msb = 0;
int lsb = 0 ;

// Qo -> 1
// Q1 -> 2
// Q2 -> 4
// Q3 -> 5
// Q4 -> 6
// Q5 -> 7
// Q6 -> 9
// Q7 -> 10

char c_array[10] = { '0', '1', '2',  '3',  '4',  '5', '6',  '7', '8', '9'} ;

int measure_voltage(){
 sensorValue = analogRead(battery_Sensor);
 return map(sensorValue, 0, 1023, 0, 50);
}

byte seven_segment(char input, bool period){
  byte output_byte;
  switch (input) {
      case '0':
        output_byte = B11101110;
        break;
      case '1':
        output_byte = B10000010;
        break;
      case '2':
        output_byte = B11001101;
        break;
      case '3':
        output_byte = B01101101;
        break;
      case '4':
        output_byte = B00101011;
        break;
      case '5':
        output_byte = B01100111;
        break;
      case '6':
        output_byte = B11100111;
        break;
      case '7':
        output_byte = B00101100;
        break;
      case '8':
        output_byte = B11101111;
        break;
      case '9':
        output_byte = B00101111;
        break;
      default:
        output_byte = B00000001;
      break;
    }
  if(period == 1){
    output_byte = output_byte ^ B00010000;
  }
  return output_byte;
}

void setup()
{
  pinMode(clock, OUTPUT); // make the clock pin an output
  pinMode(data , OUTPUT); // make the data pin an output
  pinMode(charger_ctrl, OUTPUT);
  pinMode(battery_Sensor, INPUT);

}

void loop() {
    voltage_reading = measure_voltage() ; // voltage x 10
    msb = voltage_reading/10;
    lsb = voltage_reading%10;

    shiftOut(data, clock, LSBFIRST, seven_segment(c_array[lsb], 0));// send this binary value to the shift register
    shiftOut(data, clock, LSBFIRST, seven_segment(c_array[msb], 1));
    delay(1000);
}

See the analogPinToChannel function.
static const uint8_t A0 = 6;
static const uint8_t A1 = 7;
static const uint8_t A2 = 8;
static const uint8_t A3 = 9;

...

#define analogPinToChannel(p)   ( (p) < 6 ? (p) : (p) - 6 )

Using A2, which is 8, will return 2 (8-6) from the analogPinToChannel function.
Using 4 will give 4. There is no (useful) analog channel 4.


text:
Why the GSM Shield is discontinued? What options are available?
I need to build a device with a single button to make a call over a mobile network (GSM)
I wanted to buy an arduino one and an arduino gsm shield for this, but just noticed that the GSM Shield is retired - discontinued.
I checked all the arduino products but there is no options for integration with GSM.
What options do I've to build my products if the GSM Shields is discontinued?

I don't know about South America, but GSM is obsolete. There are only a few users in most countries, the networks have been cannibalised and will shortly be shut down.

@Milliways, not really. GSM is a reliable and easy way to communicate. It is not yet obsolete.

A retired product is just a product that isn't supported anymore. It doesn't mean that this product is not usable anymore. Because the GSM shield is discontinued by Arduino.cc itself, you could buy Arduino.org (link to the GSM shield 2), or even an other model by Adafruit. Here is a link for many options of GSM shields on Adafruits' website.
A last option would be to buy it from a chinese seller on Amazon or Ebay. Though they are cheap, they are usualy very crappy and there are not many libraries for them.


text:
Attiny45 resets when setting digitalOutput to low
I currently try to program an Attiny45 with an Arduino UNO as ISP.
The Arduino is able to program the Attiny45.
However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low
(on any pin)
To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
  delay(10000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
}

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.
I tried reburning the bootloader onto the Attiny, which had no effect.

Could you show the wiring diagram?

I follwed these instructions

Including the 220Ω resistor with the LED as in the last step?

My LED can handle 5V, so I used it without, but that cant be the issue

That would be a very special LED then, if it can handle 5V without a resistor.

"Can handle" and "Is designed to work with" are two very different things. Chances are it can't handle it, but it's not getting it. Instead it is causing massive power droop from over current making the BOD trigger in the ATTiny.

If it would be the BOD, then how come that the attiny only resets, when setting the pin to low?

Ok it the resistor actually fixed it, but still. Why only when setting it to low?

Because the wiring shown there has the LED connected between the IO pin and +5V, so the IO pin, when switched LOW, turns the LED on by acting as ground.

Ok, but there I connected the LED frome the IO as output to Groud

Including the 220Ω resistor with the LED as in the last step?

...

My LED can handle 5V, so I used it without, but that cant be the issue

The one thing that "can't be the issue" is indeed the issue! Without a resistor the LED will attempt to conduct a lot of current which will damage both it and the output pin of the processor.
See The care and feeding of LEDs. From that page:

LEDs are not like normally electronic devices in that you can’t just apply a voltage to them and they work, they have to be fed the correct voltage and current to keep them happy.

And then:

There are several web sites and schematics on the web that suggest you can attach an LED directly to an Arduino output pin with no current limiting resistor. They are wrong, and following them will damage your Arduino.

So, by not using a resistor, when the output pin goes LOW it attempts to "sink" current, in order to turn on the LED. Since you have no resistor, it sinks as much as the output drivers can handle, dropping the supply voltage inside the Attiny, which then goes below the brownout level, and resets itself.
Please, when following a circuit, don't just omit bits of it, and then post a question about why it doesn't work. At least follow the circuit exactly, and then when you have learned more about electronics, you can start experimenting.

Where am I supposed to ask if not on a forum ment for it?

I searched more than enough times, so I think me asking would be totally valid.

I didn't say to not ask here, I said to follow the instructions first. You said "I followed these instructions" but you didn't. You left out part of them (the resistor). Nor did you say that in your question. You might have said "I followed the instructions but omitted the resistor which I didn't think was important".

Ok, that made more sense, then sorry if I seemed a little aggressive, and thank you :)


text:
How do I output tone() and audioFX board output through a single speaker?
I'm building a BMX start gate controller. It requires a voice sample to be played ("Riders ready, watch the gate!") before playing a series of tones at very specific frequencies and intervals. After the tones are complete, a relay is triggered which drops the start gate.
I'm intending to use one of the header pins with the tone() function to output the tones, and an Adafruit AudioFX board to play the voice sample.
How do I connect both of these to an Adafruit mono amplifier (https://www.adafruit.com/product/2130) ?
Note that only one or the other will be playing at one time.
Can I use a "passive mixer" (which I think is putting a 10kΩ resistor on each input source for the amplifier?)

Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.
I will draw a circuit in the morning.


text:
Writing new functions into progmem after main program is burned
I've been experimenting with writing very basic operating system-like programs on the Arduino, and so far I have been running user-defined programs on a small virtual machine I wrote.  This has been an interesting experience, but the VM runs on an assembly-like language and not C.
I want to be able to do something more.  I would like to be able to write a core OS, and then install new programs, written in C.  The core OS would get user input for which program to run, and then jump to that program.
Now, I know that I can do this trivially by writing the OS along with all of the programs into a single sketch. The programs are then just functions, and the OS just calls those functions.  However, I want to do this with functions I've written after I've burned the main OS.
From what I can tell, this is just a bootloader with additional user functionality.  However, I don't think that's quite right for two reasons:
First, I keep hearing that you can't write to progmem at runtime.  But isn't that what a bootloader does?  Which is correct?
Second, once a user program ends, I should return to the OS.  As far as I understand it, on the ATMega, once the main function terminates it jumps into a no-operation function and that's that.  I'd need it to jump back to the bootloader and continue the bootloader's operation.  Is that even possible?

If this is what you want to do you have chosen the wrong MCU.  Find something that can run from RAM, even if a bit inefficiently - competing ARM Cortex MCUs typically can.  Also understand that this "C" code you speak of gets compiled to machine instructions before it runs - you can compile C to instructions for a virtual machine, too.

Yes, you're right, and I've got an M0 that I can play around with.  However, I am using the AVR for a few reasons.  First, I'm familiar with it.  Second, because it doesn't just automatically have facilities to run like this I have to create them all myself.  My goal with these projects is to learn HOW those facilities are developed, not to get anything useful out of them.  So I chose a limited chip and made my own workarounds so that I understand how the more advanced chips do it all natively.

Your workaround might be an interesting puzzle, but it's not really how more capable chips would do it at all, but rather a workaround for the anachronistic limitations of the avr.

Seems you can fool the protection

@ChrisStratton: yes, you're right.  But doing it on my own means I get to make my own file system, loader style thing etc.  However, I'm actually probably going to just avoid it all and use a Cortex now that I know they CAN execute from RAM.  I guess it pays to do your homework

@Gerben nothing is being "fooled" but only delegated.  Delegating flash writing to a bit of code stored in a place where that is permissible is an old technique, for example on some MCU's you need a stub running from RAM to actually commit the flash writes.  In that case it's merely delegating from one part of flash to another.

First, I keep hearing that you can't write to progmem at runtime. But
  isn't that what a bootloader does?

Indeed. My understanding is that non-bootloader code cannot write to
the Flash, except on the smallest AVRs. You may need to check the
datasheet of your target MCU.

Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library
you provide. Just implement void exit(int status) in that library and
it will automatically override the version from avr-libc.

Yes, a quick datasheet dive reveals the following:  There are three sections in flash.  Boot is a special section where code running can actively modify progmem.  No-Read-While-Write is a section that does not allow for code to run while it is being updated (the CPU is halted).  Read-While-Write does allow for code to run while it is being updated, BUT the code that runs can only run from the NRWW section.  So it looks like I can write the OS to have an "installer" in BOOT, kernelspace in NRWW, and userspace in RWW.


text:
Why isn't the stack pointer changing in this simple sketch?
I'm playing around with context switching, and my first idea is to play with SP and see how it changes.  However, Sp doesn't do what I expect.  The sketch is below. I'm using an Uno R3.  What I expect to see is that SP should first print out some value, then it should be 4 integers further along (4x2 bytes?) when printed the second time.  But that doesn't happen, and both times I see the exact same value for SP.  What could the problem be?
    void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.print("X = ");
  Serial.println(SP,HEX);
}
void loop() {
  // put your main code here, to run repeatedly:
Serial.print("BEFORE: ");
Serial.println(SP,HEX);
int y = 15;
int z = y;
int g = z + y;
int dsf = z-y;
  Serial.println(dsf+g); //this should make these variables DO something...
  Serial.print(" After = ");
  Serial.println(SP,HEX);
  delay(1000);
}

Why do you assume that the stack will change? The AVR core has 32 registers. Plenty to store little temporary variables like those. Add to that the fact that the compiler optimizes lots of things out that it doesn't need, and you end up with almost nothing.

Valid point.  However, a similar sketch that actually called a function, whose sole role it was to print out SP, still had the SP not changing.  If I understand the function calls (perhaps I don't) then at least the return address should be on the stack at that point, shouldn't it?

You should examine the compiled assembly code to see what it's actually doing.

You should also read this: https://gcc.gnu.org/wiki/avr-gcc - especially the calling convention and frame layout sections

Thanks, will do.  If you summarize the comments as an answer I'll accept

You can use setjmp/longjmp for context switching. Please see https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/src/Scheduler.cpp#L124 as an example.

@MikaelPatel: I've set/jumped a bunch in previous code.  However, I want to do it on my own to see how it's done.  Otherwise I'd just download FreeRTOS or something

@MichaelStachowsky That is the spirit! Here is a link that might provide some insight. https://github.com/vancegroup-mirrors/avr-libc/blob/master/avr-libc/libc/stdlib/setjmp.S Writing that in C/C++ would provide an extra challenge :)

It's impossible to second-guess the compiler like that. There's a couple of things you need to realise:

The compiler will optimize out any variables that just get assigned to other variables as part of calculations and have no further use
The AVR CPU has 32 registers. More than enough to not need to use RAM to store values for a simple sketch like that.

Making the variables volatile will certainly help, since that forces the compiler to place them in memory. However you really should examine the assembly code the compiler produces to know exactly what it's doing.

Another way the compiler can optimize is to compile small or single-use functions inline. What you expected would get wrapped inside a call and return sequence, may not.
Inserting __attribute__ ((noinline)) ahead of the function definition can suppress that optimization:
__attribute__ ((noinline)) void foo(int bar)
{
   // do something
}

suppresses the inlining for function foo(). Inlining has frustrated my investigations more than once, so I created this easier to remember macro. (The keyword is just __NOINLINE; the #else-clause is there so that, umm, "someone", doesn't unwittingly try to use the "__attribute..." declarator with another compiler that doesn't recognize it).
// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

Even small multi-use functions might be inlined.

I noticed that gcc is way more prone to inlining since the Arduino IDE started giving it the -flto compiler option. Before that point, it would not inline any non-trivial non-static function.

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


text:
Serial question : Going from Mega to Uno
I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB
 /*
Arduino Neato XV-11 Laser Distance Scanner
Motor control board v0.2 by Cheng-Lung Lee

XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
data from the data stream to do speed control on LDS motor. Everythin can power
from USB no extra power required.

Change log:
V0.2 Add simple speed control code update PWM 3 times per rev.
V0.1 Opend loop control version.

This code is tested on Arduino Mega 1280
I/O:
Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
Neato XV-11 LDS Vcc(red) : 5V
Neato XV-11 LDS TX(Orange) : RX3

 */

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

 void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

  // prints title with ending line break
  Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

  // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

UNO only has one hardware UART, hence only one Serial, which is linked to USB, but you could still use it for something else by connecting to directly to D0 & D1. However, if you need 2 UART then go for SoftwareSerial.

Thank you, so I need to read on 1 serial (lidar) and stream to the USB?

If you need only RX on one side (lidar) and only TX on the other side (USB), then that should work, provided both links work at same speed and settings (parity...) Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with lidar input.

Oh great thats awesome, maybe post that as the answer.  So I am fine to read from RX0 and write to Serial (USB)

Arduino UNO only has one hardware UART, hence only one Serial available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.
However, if you need 2 separate, independent, UART then go for SoftwareSerial for the second one.
Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. Serial for both devices, as long as both links work at the same speed and settings (parity...)
Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.
The non USB device providing input to the Uno should be connected to D0 (RX).

authors: บรรพต โสดากุล


text:
Serial 3 vs Software Serial
So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered)  I tried to use Serial (D0) to read and then write to serial, which did not work.  So now I am looking in to Software Serials
Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower
#include <SoftwareSerial.h>

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

    // prints title with ending line break
    Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

    // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );

    mySerial.begin(115200);
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

  if (mySerial.available() > 0) {
    // get incoming byte:
    inByte = mySerial.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

There are huge differences. The most important ones are:

SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).

Ok thank you, damn I need 2 serial ports then. I read on the serial and send on to USB.

That is often the case. That is why Atmel came up with the "upgrade" of the ATMega328PB which has a second UART. Another good choice is the ATMega32U4 (as used on the Leonardo) which separates the USB from the UART so you can use both separately.

Oh brilliant, I only need it for this project, so I should get a Leonardo,  hopefully it's smaller than the mega

It's the same footprint as the Uno.

Thanks you :) out of scope I know but any down point? Like not compatible with shield etc. Assuming the Leonardo uses serial1

If you want even smaller there is the Arduino Micro that has the same chip as the Leonardo.

The Leonardo has the real UART on pins 0/1 like the Uno. IIRC SPI and I2C may be in different places compared to the Uno.

I will go and read up, but I am assuming my code above won't need much work

Serial is the USB virtual UART, and Serial1 is the real UART (IIRC)


text:
Possibility of getting a UID on Arduino
Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.
The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

Does the arduino have a UID like some sort of MAC code?
What could be a solution to give the Arduino a UID?
Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

What LoRa modules are you using?

For now Im not using any, but I should be going to use the SX1276 Inair9b. Currently the data comes in over USB, but having no UID will be a problem.

Some LoRa modules contain a UID that you can use, but that one doesn't appear to. You have 4 main options: 1. hard code a UID in the firmware, 2. Provide an interface (UART?) to set the UID in EEPROM, 3. use external configuration switches or jumpers to set the UID, or 4. use an external UUID chip.

Generate a random number and store it in the EEPROM (if after reading the EEPROM returns zero). Or have the base station generate I'd that you can get through Lora.

Add a 1-Wire device such as DS18B20 to your design and use the ROM identity from that.

Possible duplicate of How can I get a unique ID for all my Arduino boards?

@jfpoilpret It is basically the same question, but it did get other answers. And the answers given to the other question didn't 'solve' my problem right away. Also no answer was accepted.
This is one of these questions with multiple answers and therefore I can't really say the other question has the correct answer.

You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)
An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.


text:
Scrambled query responses from ESP8266 to Uno, what are possible causes of the problem?
I have a small test sketch that sends queries to an ESP8266 chip [mounted on an ESP-01 board], and these responses are invariably scrambled,
though the response varies from execution to execution, e.g.,
(execution 1)
_________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAX="I⸮Tcircuiz2",""H

(execution 2)
__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAH="KCTcircuiz2!,""H

What could be the source of the problem?  I need to resolve this before I can start testing the real sketch.
My test sketch follows [stripped of extraneous code]:
#include <SoftwareSerial.h>
// _______________________________
#define sendit(x) ( { \
    Serial.print(F("__________[ ")); \
    Serial.print(x); \
    Serial.println(F(" ]__________")); \
    esp8266.write(x); \
    esp8266.write(F("\r\n")); \
    esp8266.readBytes(buffer, sizeof(buffer)); \
    Serial.println(buffer); \
    delay(2000); \
  } )

// _______________________________
#define desc(x) ( { \
    Serial.println(); \
    Serial.print(F("__________[ ")); \
    Serial.print(F(x)); \
    Serial.println(F(" ]__________")); \
  } )

// _______________________________
SoftwareSerial esp8266(12, 13); // RX, TX
char buffer[50];

// _______________________________
void setup()
{
    Initialise();
}

// _______________________________
void loop()
{
}

// ____________________________________________________________________________________________________
void Initialise()
{
    SerialReadBuffer.reserve(64);
    esp8266.begin(115200);
    Serial.begin(9600);
    CommandList();
}

// ____________________________________________________________________________________________________
void CommandList()
{
  desc("Test AT Startup");
  sendit("AT");
  desc("Restart the module");
  sendit("AT+RST");
  desc("Query baud rate");
  sendit("AT+CIOBAUD?");
  desc("Query firmware version");
  sendit("AT+GMR");
  desc("WIFI mode");
  sendit("AT+CWMODE?");
  desc("Get local IP address");
  sendit("AT+CIFSR=?");
  desc("Query current multiplex mode");
  sendit("AT+CIPMUX=?");
  desc("Enable echo (Sends back received command before response)");
  sendit("ATE1");
  desc("Set Station mode");
  sendit("AT+CWMODE=3");
  desc("Lists available APs");
  sendit("AT+CWLAP");
  sendit("AT+CWLAP");
    desc("Connect to AP");
  sendit("AT+CWJAP=\"KCTcircuit2\",\"\"");
  desc("Prints the SSID of Access Point ESP8266 is connected to.");
  sendit("AT+CWJAP?");
  desc("List clients connected to ESP8266 softAP");
  sendit("AT+CWLIF");
  desc("Get IP address of ESP8266 station.");
  sendit("AT+CIPSTA?");
  desc("Get information about connection");
  sendit("AT+CIPSTATUS=?");
  desc("Get local IP address");
  sendit("AT+CIFSR=?");
  desc("Get the SSID of Access Point ESP8266 is connected to.");
  sendit("AT+CWJAP?");
  desc("Get the SSID of Access Point ESP8266 is connected to -CUR");
  sendit("AT+CWJAP_CUR?");
  desc("Configuration of softAP mode");
  sendit("AT+CWSAP?");
  desc("Configuration of softAP mode = CUR");
  sendit("AT+CWSAP_CUR?");
  desc("Disconnect from AP");
  sendit("AT+CWQAP");
  Serial.println(F("__________________"));
  Serial.println();
 }

Typical output is as follows:
"ESP8266_ATcmdtest", compiled on: Jun  5 2017 at 14:00:04
Running on: Arduino UNO: ATmega328P

__________[ Test AT Startup ]__________
__________[ AT ]__________
ATn

__________[ Restart the module ]__________
__________[ AT+RST ]__________
AT+QST$

__________[ Query baud rate ]__________
__________[ AT+CIOBAUD? ]__________
AT+CHOBAUD⸮⸮

__________[ Query firmware version ]__________
__________[ AT+GMR ]__________
AT+TJ⸮⸮AUD⸮⸮

__________[ WIFI mode ]__________
__________[ AT+CWMODE? ]__________
AT+CWLODE?G⸮

__________[ Get local IP address ]__________
__________[ AT+CIFSR=? ]__________
AT+CHFSR=?⸮

__________[ Query current multiplex mode ]__________
__________[ AT+CIPMUX=? ]__________
AT+CIPMUX=r⸮

__________[ Enable echo (Sends back received command before response) ]__________
__________[ ATE1 ]__________
ATE0=PMUX=r⸮

__________[ Set Station mode ]__________
__________[ AT+CWMODE=3 ]__________
AT+CWMODE=⸮⸮

__________[ Lists available APs ]__________
__________[ AT+CWLAP ]__________
AJ+CWL@P⸮=⸮⸮
__________[ AT+CWLAP ]__________
AT+CWLAP⸮=⸮⸮

__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAH="KCTcircuiz2!,""H

__________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
AT+CWJAP?⸮KCTcircuiz2!,""H

__________[ List clients connected to ESP8266 softAP ]__________
__________[ AT+CWLIF ]__________
AV+CWLIFx⸮KCTcircuiz2!,""H

__________[ Get IP address of ESP8266 station. ]__________
__________[ AT+CIPSTA? ]__________
AT+CIPSTA?CTcircuiz2!,""H

__________[ Get information about connection ]__________
__________[ AT+CIPSTATUS=? ]__________
AT+CIP*UQUM⸮⸮2ircuiz2!,""H

__________[ Get local IP address ]__________
__________[ AT+CIFSR=? ]__________
AT+CIFSR=?}⸮⸮2ircuiz2!,""H

__________[ Get the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
AT+CWJAP? }⸮⸮2ircuiz2!,""H

__________[ Get the SSID of Access Point ESP8266 is connected to -CUR ]__________
__________[ AT+CWJAP_CUR? ]__________
AT+CW⸮AP5UI⸮⸮⸮ircuiz2!,""H

__________[ Configuration of softAP mode ]__________
__________[ AT+CWSAP? ]__________
AT+CWSAP?HI⸮⸮⸮ircuiz2!,""H

__________[ Configuration of softAP mode = CUR ]__________
__________[ AT+CWSAP_CUR? ]__________
AT+CWSAP5UI⸮r⸮ircuiz2!,""H

__________[ Disconnect from AP ]__________
__________[ AT+CWQAP ]__________
AZ+CWPAP⸮UI⸮r⸮ircuiz2!,""H
__________________

I also have another, simpler, sketch that accepts commands from the Serial Monitor instead.  It has equivalent behaviour in terms of responses.

Cause: software serial at 115200 baud.
Solution: configure the esp8266 for a lower baud rate or use hardware serial.
The problem is basically that the Arduino cannot run 115200 baud SoftwareSerial reliably. It is common to get corruption of incoming characters, or characters completely skipped, due in part to the SoftwareSerial implementation being unable to react fast enough to the data coming in. The time between one stop bit and the next start bit is often shorter than the amount of time taken to store the data in the receive ring buffer, so the ISR cannot respond to the new start bit in time, and data is lost.  Running at a lower baud rate gives more time for the data to be stored before the next start bit arrives, thus giving the ISR time to finish and be ready to respond to the next byte coming in.
You need to change the baud rate of the ESP8266 itself (I find 9600 is a good reliable value) using one of (depending on your firmware version):
AT+CIOBAUD=9600

or
AT+UART_DEF=9600,8,1,0,0

or
AT+IPR=9600

Last time I did it on an ESP8266 it was the first one that worked.
Then you will need to change your program to use 9600 baud instead of 115200 baud in your esp8266.begin(...).

Though not mentioned above, I have tried also 9600, 19200, 38400, 57600.  All are indecipherable, except for 9600, which yields absolutely nothing.  115200 is the only one that even approximates a proper response.

I have also used multiple ESP8266 chips, plus different Uno and Mega2560 boards.

@KCTucker: yes, the module is set too high, that's what he's saying. once you lower it, it will not only work, it will work without the glitches you're asking about.

@Majenko For clarification, I found that AT+IPR worked fine, as, apparently, would AT+UART_DEF=9600,8,1,0,0.
However, the change effected by AT+CIOBAUD was not sustaining.
A reference @ http://www.esp8266.com/viewtopic.php?f=13&t=718
indicates that AT+CIOBAUD changes the baudrate only temporarily, which matches my own experience.

Since you mentioned you tried other baud rates, I am guessing it could be an RF issue. ESP8266 is a very sensitive device and is known to have weird electrical behaviour. Do you have a cap between VCC and GND?

You could try a lower baud rate, it might work but still isn't a solution. Which board are you using? 115200 works just fine on my NodeMCU.

BTW, you do know right that you don't really need two boards. You can program the ESP in Arduino IDE itself, using Arduino code.

Of course.  This is just a simple test script.  The actual script requires 11 data pins though.


text:
How does one set attributes for SD files?
How does one set file attributes, e.g., creation date, for a file being created on an SD?

The Arduino SD library, is based on Github: greiman/SdFat, by William Greiman.
From SD Created File Attributes:

The basic SD.h library doesn't set the attributes. You notice everything has the same creation date? The library doesn't have any way of knowing what the date is.

However, you need to use a callback function. The following information is from file creation date and time in sd card ?:

Install the SdFat library - there is an example called Timestamp.ino describing in detail how to do it...
// after your rtc is set up and working you code just needs:

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = rtc.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

//put that outside of any functions, before your 'setup'

//Then inside your 'loop' or 'setup'

void loop(void)
{

  //Other code that does stuff

  //put this next line *Right Before* any file open line:
  SdFile::dateTimeCallback(dateTime);
  dataFile = SD.open(datafilename, FILE_WRITE);

  //other code that does stuff

}

There is another way of achieving this, in a sketch without having to convert to SDFat:

@donald0000 wants the Date Modified field to show an actual time stamp
  when you look at the files present on the card using Windows Explorer.
  As Billy Ho says, the callback function is the way to do it. You can
  indeed use this function with SD.h  if you don't want to convert to
  SDFat. Here is an example of the function in a sketch. Notice the
  timing of when the date modified time stamp is written, it is when
  file.close() writes the actual data to the card.
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <RTClib.h>

File file;  // test file
const uint8_t SD_CS = 10; // SD chip select
RTC_DS1307 RTC;  // define the Real Time Clock object

 char timestamp[30];

//------------------------------------------------------------------------------
// call back for file timestamps
void dateTime(uint16_t* date, uint16_t* time) {
 DateTime now = RTC.now();
 sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
 Serial.println("yy");
 Serial.println(timestamp);
 // return date using FAT_DATE macro to format fields
 *date = FAT_DATE(now.year(), now.month(), now.day());

 // return time using FAT_TIME macro to format fields
 *time = FAT_TIME(now.hour(), now.minute(), now.second());
}
//------------------------------------------------------------------------------
void setup() {

 Serial.begin(9600);
 Wire.begin();
 if (!RTC.begin()) {
   Serial.println("RTC failed");
   while(1);
 };
 // set date time callback function
 SdFile::dateTimeCallback(dateTime);

  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(),now.minute(),now.second(),now.month(),now.day(),now.year()-2000);
  Serial.println("xx");
  Serial.println(timestamp);

 if (!SD.begin(SD_CS)) {
   Serial.println("SD.begin failed");
   while(1);
 }
 file = SD.open("TEST_SD.TXT", FILE_WRITE);
 file.println("Testing 1,2,3...");

 delay(5000);
 file.close();
 Serial.println("Done");
}
//------------------------------------------------------------------------------
void loop() {}

Quite simply FAT16 only supports 1 date, normally Modified Date. FAT32 has (limited) support for 3 dates (but AFAIK there is no Arduino library which supports FAT32).
Even then not all OS even support Creation Date. Windows has 2 different interpretations depending on application, Linux natively only supports Change Date, although extensions provide support for more dates.

the latest SDFAT library supports FAT32.


text:
How to control low power devices when implementing Low Power Mode strategy?
As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver.  I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma.
Should I be using MOSFET and, if so which one?  Else, what is a better solution?  The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.

my fav is the IRLZ44N, which are easy to drive from ardunio with a Vgs(th) of a couple volts, built-in dioide, a tiny on-resistance, and up to 55v of switching at 47amps. if you switch less than 20v, a common ground works perfectly with a simple N-chan circuit w/o extra bjt helpers

Yes, MOSFETs are what you want.
The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.
So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.
Here's two schemes:

simulate this circuit – Schematic created using CircuitLab
In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.
In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).
One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).
All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).

How, then, do I go about the process of selecting a suitable MOSFET to utilise?

Find one where a) the on resistance is low enough (you want sub 1Ω, better sub 0.1Ω) when V_GS is at your switching voltage (5V), so one with a threshold of no more than a volt or two, and b) can handle the current flow (and heat dissipation) that you require at that V_GS.

IRF540 seems like a suitable choice.  However, I am rather less than confident in my ability to properly analyse the myriad of spec. sheets.  I will use that until I determine it is a bad decision..


text:
Problem using HC-12 graphical configuration utility, invalid responses
I'm trying to use this utility [first time] to config a pair of HC-12s to a different channel, as I already have the default address in use.  It's a very handy utility, though I can find almost no reference to it via Google.
I found reference to the command here:
http://www.thebackshed.com/forum/forum_posts.asp?TID=8246&PN=1
When I use to change the channel, i get 5 error messages of the form:
invalid response(1),
invalid response(3.2),
invalid response(3.3),
invalid response(3.4),
invalid response(3.5)
I am running on Windows 10 x6, using a standard USB cable to an Uno.
The wiring config is as follows:
VCC to 5v,
GND to GND,
RXD to pin 4,
TXD to pin 5,
Set to pin 6
I've also tried connecting the Set pin to GND, as I don't know whether this is necessary or not.
The board also has an 1N4007 diode in series with the power line, and a 1000uf capacitor twixt 5v and GND.  Nothing else.
There is a sample program at:
http://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/
that should accomplish the same function via use of line commands and I shall try that next.  However, the configuration utility is so handy that I would like to have it in my kit of useful tools.
Seeking:
Assistance with the graphical configuration utility by someone who knows more than I, or perhaps a better alternative.

the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.
if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.
feel free to join the backshed forums and ask further questions about the HC-12.
cheers,
robert rozee
(author of the HC-12 config utility)


text:
esp8266 esp-01 crashing, restarting over and over
I flashed my ESP-01 with the nodemcu firmware 512k version, and everything was working fine.  I testing some lua scripting on init.lua and it was working.  Then, after writing a bunch of code and uploading, the module restarted.  And it restarted.  And it's still restarting, over and over again, and prints to serial
CÀbc0°ýbcü¨HøNodeMcu 0.9.4 build 20141230  powered by Lua 5.1.4
ö,3bþÈH

It was always printing the garbage in there before, so I'm not worried about that.  However, I can't send anything to the device--I can't send serial commands, or reflash the device.  I'm thinking I overloaded the memory or something.  Anyone have any ideas for recovering this brick?

This is really not the right website for this question.  If you were running a port of the Arduino framework to the ESP8266, that might barely be a fit (though still much better supported on an ESP8266 site), but here your question concerns neither Arduino-type hardware nor software.

Turns out I was pulling up on the GPIO0 pin, instead of down.  Ensure you have the correct pin-out when flashing.
ESP-01 VCC - 3.3v Serial Adapter
ESP-01 GND - Ground or Minus Serial Adapter
ESP-01 RX - Connect to TX on Serial Adapter
ESP-01 TX - Connect to RX on Serial Adapter
ESP-01 CH_PD - 3.3v Serial Adapter
ESP-01 GPIO0 - Pull low by connecting to ground / minus
There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over.  That is also what was happening.  There is some problem with wifi.sta.getap() that exacerbates this.


text:
Conveyor and Counter Project
I am new to Arduino and looking for advice if Arduino is the right microcontroller for this project.
My project is quite simple, I want to build 3 conveyors using 3 DC motors. At the end of each conveyor I plan to implement 3 IR break beam sensors to each respective conveyor to count when an object passes through. When n objects passes through each respective conveyor and falls into a catching mechanism the DC motor stops until object(s) are cleared. For the catching mechanism for each conveyor, I plan to use IR break beam sensors to detect if it’s cleared or not as well. (If you have an alternative suggestion to IR break beam sensors, please advice)
Question: Can a single Arduino uno microcontroller board handle this project? From what I know, Arduino can only run one program at a time and I’m not sure if my project can be run in one program; I believe it can. Additionally, what if I wanted to add a LCD display?

Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)

Thanks for the clarification on how a single Arduino unit can handle this project. And yes, the cost of industrial conveyors are crazy high!! Also, I will look into separating the systems but is it possible to start all 3 with a single input?

3 motors, 3 IR "counters", 3 IR "check empty" that gives us 9 pins (3 out, 6 in) arduino has 13 digital pins so no problem there. And if you would use I2C protocol for sensors (it's very popular) you can hook up to 1023 sensors to a single arduino (usung only 2 pins of the Arduino)


text:
Can an Arduino power itself off [not low power mode] via software?
I'm working on a sketch where an Arduino UNO performs no useful work after the first 10 minutes following power on.  It is not needed again until power to it is shut down, then re-enabled.  This may not happen for hours or even days.  No wake-up function is required, or deemed useful.
Of course, the Arduino could simply be left on as long as it's connected to its power source, but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.
In essence, the Arduino is powered by a wall wart and plugged in with other devices fed by a switchable 120v power source.
I found a couple of possible hardware/software solutions to the problem but it isn't clear whether they would work in this situation.  Power consumption is not the issue here.

you can interrupt the input voltage with a relay that both an exgternal trigger and a GPIO pin can control. A brief trigger gives the relay power, which powers the uno. The uno writes the pin high in setup(), keeping the relay on. Once done, the pin is written low and the uno turns off.

Based on feedback, it seems clear that any solution to this problem will require the addition of hardware, and the use of a specific type of relay presents a simple solution that will satisfy my needs. In my situation, the requirement is for the Arduino to turn off after a specific amount of time. It really is not necessary for the Arduino itself to trigger the action, just that it is shut off once the interval lapses. As such, a very simple circuit can be constructed using a programmable timer relay delay switch to front-end the Arduino, setting the time delay that is needed. The Arduino is n

A battery-powered Arduino can go into deep sleep mode where it can use as little as 100 nA, and still be woken by a switch closure if required.
There doesn't seem to be much point to me to power down a mains-powered Arduino. What would be the purpose of that?  The small amount of current it would use via the wall-wart would be trivial. If you are worried about voltage spikes (eg. lightning) then you should protect the input pins (or your power supply) whether or not it is powered off.
It seems to me that you may as well do whatever you need to do, and then go into an infinite loop. Once the Arduino is re-powered it will do it again. You aren't saving much by attempting to power it off, indeed that introduces an extra point which might fail.

but it will be placed remotely, and it seems [to me] safer to have it powered off. when not in use.

Safer in what way? Any extra hardware you introduce to make the Arduino "safer" might itself introduce safety issues. It reminds me of the days when we had a UPS (Uninterruptable Power Supply). The UPS would fail more-or-less as often as the power did. In other words, you replaced one possible failure (the power failure) with another possible failure (the UPS failure).

I think, that OP thinks around the way - no power = no possible shortcuts from condesated watter drops or other external shortcut devices - the same reason many people plug of electronics from socket, when they leave for vacation.

In general, an Arduino by itself has no control over its power input.  It can, of course, enter various Sleep modes, such as the Power-down mode with watch-dog-timer off, which uses 0.1  μA.
It isn't clear from the question what will turn the Arduino back on after it is off for a while, but if you have either a push-button or a signal to turn it back on, the Pololu 2808 Mini Pushbutton Power Switch will work as an Arduino-controlled off switch.  This board has On, Off, Ctrl, and button-contacts inputs.  If your Arduino raises the Off input, power shuts off cleanly.  To turn it back on, either connect the  button-contacts inputs together, or raise the On input, or pulse the Ctrl input.

No buttons or signals utilised.  The Arduino power supply would be cut off at some point by virtue of an unrelated action, i.e., it resides on a circuit that would be powered off for other reasons, e.g., to disable all attached devices.  I am just trying to work out how to power off the Arduino in advance of that action.
At some point, that circuit would be powered back on again, and consequently the Arduino would power up again, reboot, and run its sketch for a few minutes.  Once that is completed, the Arduino has nothing else to do until the entire sequence is repeated.

As far as I can tell, I am trying to achieve something here that is rather different that the objectives one usually encounters.


text:
Using ESP8266 to send email. However "HELO" responds with "ERROR". Possible cause?
I am developing a sketch that uses an Uno and an ESP8266 to send email via smtp2go.  However "HELO" responds with "ERROR".  What might be the source of the problem?
To explore this, I created another sketch that simply sends commands to the ESP8266, and displays the results.
The wifi connection seems fine, as does the SMTP Server connect to mail.smtp2go.com.
However, the next command issued "HELO 10.1.0.35" provides a response of "ERROR".
The ESP8266 is  mounted on an ESP-01 board, and set @ 9600 baud.  have tested with different chip sets.
I have also tried using Gmail [smtp.gmail.com,465 ], but results are the same.
[I know that an ESP8266 can be used stand-alone.  However the final sketch requires 13 data pins.]
Output from sketch:
"ESP8266_ATcmdtest", compiled on: Jun  8 2017 at 17:58:18
Running on: Arduino UNO: ATmega328P

__________[ Disable echo (Echo sends back received command before response) ]__________
__________[ ATE0 ]__________
Response buffer:
OK

__________[ Delete server ]__________
__________[ AT+CIPSERVER=0 ]__________
Response buffer:
no change
OK

__________[ Restart the module ]__________
__________[ AT+RST ]__________
Response buffer:
OK
0,CLOSED
WIFI DISCONNECT
bB׆QR⸮⸮⸮ȤRN⸮ɥRL⸮H⸮⸮N⸮⸮d#@⸮⸮
WIFI CONNECTED

__________[ Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45) ]__________
__________[ AT+GMR ]__________
Response buffer:
AT+GMR
AT version:1.2.0.0(Jul  1 2016 20:04:45)
SDK version:WIFI GOT IP

__________[ Lists available APs ]__________
__________[ AT+CWLAP ]__________
Response buffer:
AT+CWLAP

+CWLAP:(0,"KCTcircuit2",-47,"08:bd:43:ff:6a:0c",1,21,0)
+CWLAP:(3,"49KHC",-88,"70:f1:96:66:29:ef",1,11,0)
+CWLAP:(3,"KCTstudy",-49,"04:a1:51:bf:6b:30",5,-11,0)
+CWLAP:(3,"Linksys05761",-75,"b4:75:0
e:64:54:b1",11,21,0)
+CWLAP:(3,"Pccd_main",-91,"14:91:82:83:f8

__________[ Get local IP address, e.g., 192.168.4.1 ]__________
__________[ AT+CIFSR ]__________
Response buffer:
AT+CIFSR
+CIFSR:STAIP,"10.0.0.4"
+CIFSR:STAMAC,"5c:cf:7f:34:

__________[ Set Station mode ]__________
__________[ AT+CWMODE=1 ]__________
Response buffer:
AT+CWMODE=1
OK

__________[ Set current multiplex mode ]__________
__________[ AT+CIPMUX=1 ]__________
Response buffer:
AT+CIPMUX=1

OK

__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTstudy","[pw redacted]" ]__________
Response buffer:
AT+CWJAP="KCTstudy","[pw redacted]"
WIFI DISCONNECT
WIFI CONNECTED

__________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
Response buffer:
AT+CWJAP?
busy p...
WIFI GOT IP

OK

__________[ Get IP address of ESP8266 station, e.g., 10.0.0.4 ]__________
__________[ AT+CIPSTA? ]__________
Response buffer:
AT+CIPSTA?
+CIPSTA:ip:"10.0.0.4"
+CIPSTA:gateway:"10.0.0.1"

__________[ SMTPServer connect ]__________
__________[ AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525 ]__________
Response buffer:
AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525
0,CONNECT

OK

+IPD,0,70:220 mail.smtp2go.com ESMTP Exim 4.87 Fri, 09 Jun 2017 00:59:07 +0000

__________[ Get information about connection ]__________
Response format  is:
STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]
+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]
OK
__________[ AT+CIPSTATUS ]__________
Response buffer:
AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","173.255.233.87",25

__________[ HELO ]__________
__________[ HELO 10.0.0.8 ]__________
Response buffer:
HELO 10.0.0.4
ERROR

Sketch code
#include <SoftwareSerial.h>

// _______________________________
#define sendit(x) ( { \
    Serial.print(F("__________[ ")); \
    Serial.print(x); \
    Serial.println(F(" ]__________")); \
     esp8266.write(x); \
   esp8266.write("\r\n"); \
     delay(300); \
     Serial.println(F("Response buffer: ")); \
     for (int i=0; i <= 99; i++) { \
         memset(buffer, 0, sizeof(buffer)); \
         delay(10); \
       bcount = esp8266.readBytes(buffer, sizeof(buffer)); \
           if (bcount == 0)  i = 100; \
           else { \
    if (bcount > 1) Serial.println(buffer); \
    delay(300); \
      } \
    } \
  } )

// _______________________________
#define desc(x) ( { \
    Serial.println(); \
    Serial.print(F("__________[ ")); \
    Serial.print(F(x)); \
    Serial.println(F(" ]__________")); \
  } )

// _______________________________
SoftwareSerial esp8266(11, 12); // RX, TX
char buffer[200];
String SerialReadBuffer = "";
char SerialByteIn; // Temporary variable
boolean SerialEnd = false;
int bcount;

// _______________________________
void setup()
{
    Initialise();
}

// _______________________________
void loop()
{
}

// ____________________________________________________________________________________________________
void Initialise()
{
    SerialReadBuffer.reserve(64);
    esp8266.begin(9600);
        // esp8266.begin(115200);
    Serial.begin(9600);
    CommandList2();
}

// ____________________________________________________________________________________________________
void CommandList2()
{
    desc("Disable echo (Echo sends back received command before response)");
    sendit("ATE0");
    desc("Delete server");
    sendit("AT+CIPSERVER=0");
    desc("Restart the module");
    sendit("AT+RST");
    desc("Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45)");
    sendit("AT+GMR");
    desc("Lists available APs");
    sendit("AT+CWLAP");
    desc("Get local IP address, e.g., 192.168.4.1");
    sendit("AT+CIFSR");
    desc("Set Station mode");
    sendit("AT+CWMODE=1");
    desc("Set current multiplex mode");
    sendit("AT+CIPMUX=1");
    desc("Connect to AP");
    sendit("AT+CWJAP=\"KCTstudy\",\"[pw redacted]\"");
    desc("Prints the SSID of Access Point ESP8266 is connected to.");
    sendit("AT+CWJAP?");
    desc("Get IP address of ESP8266 station, e.g., 10.0.0.4");
    sendit("AT+CIPSTA?");
    desc("SMTPServer connect");
    sendit("AT+CIPSTART=0,\"TCP\",\"mail.smtp2go.com\",25");
    desc("Get information about connection");
    Serial.println(F("Response format  is: "));
    Serial.println(F("STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]"));
    Serial.println(F("+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]"));
    Serial.println(F("OK"));
    sendit("AT+CIPSTATUS");
    //
    // Problems start here
    //
    desc("HELO");
    sendit("HELO 10.0.0.4");
    Serial.println(F("__________________"));
}

in my (limited) experience, anything beyond pushing and fetching http transactions is flaky and difficult on the AT firmware. You can run a nice custom sketch on the ESP and still use serial to talk to the ardunio, using your own commands instead of the AT ones. The debugging differences are extreme; total flexibility and intermediate logging vs a "black box" with cryptic returns. that also lets you use the pins on the ESP if needed, store 3mb of data locally, etc etc...

@Look Alterno, I am not very savvy on this subject, but no NAT router or private SMTP server.  I have this problem only when using with the ESP8266.
I have 3 other Arduino systems using  Ethernet shields instead and accessing the same network.  These work fine for sending the same kind of Email.
For the ESP8266 system, there is simply no Ethernet cable connect available.  I have still not sorted this out yet.

You're sending the word "HELO" to the ESP8266 and the ESP8266 is, quite rightly, saying "What?!?! I don't know the command HELO!"
You have opened a connection in multiple connection mode with ID 0. You then have to send data through that connection.  For instance:
AT+CIPSTART=0,"TCP\","mail.smtp2go.com",2525
OK
AT+CIPSEND=0,15
> HELO 10.0.0.4<CR><LF>
SEND OK

Using a protocol like SMTP in this mode is not easy. Better would be to use "unvarnished" mode:
AT+CIPSTART="TCP","mail.smtp2go.com",2525
OK
Linked
AT+CIPMODE=1
OK
AT+CIPSEND
> HELO 10.0.0.4<CR><LF>
250 mail.smtp2go.com Hello 10.0.0.4 [23.114.28.226]
MAIL FROM: "Foo Bar" <foo@bar.com>
250 OK
... etc ...
QUIT
221 mail.smtp2go.com closing connection

Note that just sending commands and blindly printing the responses isn't really the best way to go about it. You should be actively interpreting the responses that you get back and making decisions based upon them. Especially when you're in SEND mode. The SMTP protocol is two-way. You need to know what the responses are saying and what that means for your SMTP session.

Before sending "HELO 10.0.0.4" ... you should send a CIPsend command with the length of your sentence + 2
Here is the right command sequence:
AT+CIPSEND=4,15
HELO 10.0.0.4

Best regards


text:
Conditional compilation, how to determine whether a variable has been declared?
Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?,
e.g.,
#if [the variable "pinname" has been declared]
Serial.print(F("Pin name: "));
Serial.println(pinname);
#end

If this question has been addressed, I cannot find a reference for it.

Normally you use the "#ifdef" directive.
The opposite is "#ifndef".
For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my_variables.h":
#ifndef MY_VARIABLES_H
#def MY_VARIABLES_H

int counter;
bool flag;

#endif

In this way, no matter how many times you include this file, you only define the variables once.  Because after the 1st time the compiler sees this file, the variable MY_VARIABLES_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.

You cannot. Simple as that.
I suspect this is an XY Problem. If you edit your post stating what you're actually trying to do, I'll edit my answer (or delete it if I don't know).

my example is exactly what I am trying to do.
@Mark Smith, In this case, specific variables and names are defined based on board attributes.  Another routine is attempting to display such, but obviously only for defined variables.  Of course, I can handle this with the necessary book-keeping.  However, I'd like to know if there is a simpler solution.  If not, I know exactly how to get the results i want.

authors: Ричард Хасанов