text:
Serial input help
Hey guys I have a LED strip with 6 LEDS
(I control these through Kinect & processing. It sends 1,2,3,4,5,6 to Arduino. This seems to work fine.)
In Arduino LED0,LED1,LED2,LED3,LED4 work perfectly but the last one don't work. it doesn't light up at all.
Anyone know what's going on?

#include <FastLED.h>

#define LED_PIN     13
#define NUM_LEDS    6

CRGB leds[NUM_LEDS];

void setup() {

  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(9600);

}

void loop() {

  if (Serial.available() > 0) {
int incomingByte = Serial.read();

  //1
if(incomingByte=='1'){
  leds[0] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}

 //2
 if(incomingByte=='1'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[1] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
  if(incomingByte=='4'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}

  //3
   if(incomingByte=='1'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[2] = CRGB(255, 0, 0);
  FastLED.show();}
   if(incomingByte=='4'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}

  //4
   if(incomingByte=='1'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
    if(incomingByte=='4'){
  leds[3] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}

  //5
   if(incomingByte=='1'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[4] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}

  //6
   if(incomingByte=='1'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();
if(incomingByte=='2'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[5] = CRGB(255, 0, 0);
  FastLED.show();}

}
  }
}

here's the processing code:
float x = 100;
float y = 50;
float w = 150;
float h = 80;

import org.openkinect.freenect.*;
import org.openkinect.processing.*;
import processing.serial.*;

// The kinect stuff is happening in another class
KinectTracker tracker;
Kinect kinect;
Serial myPort;

void setup() {
  size(512, 424);
  kinect = new Kinect(this);
  tracker = new KinectTracker();
  String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw() {

  tracker.track();
  tracker.display();

  PVector v1 = tracker.getPos();
  fill(50, 100, 250, 200);
  noStroke();
  ellipse(v1.x, v1.y, 50, 50);

   //1
    if (v1.x > 0 && v1.x < 50 ){
    println('1');
    //rect(0,200,200,200);
    myPort.write('1'); }
    //println('0'); }

    //2
  if (v1.x > 50 && v1.x < 100){
    println('2');
    myPort.write('2'); }
 //3
   if (v1.x > 100 && v1.x < 150 ){
    println('3');
    myPort.write('3'); }

    //4
   if (v1.x > 150 && v1.x < 200 ){
    println('4');
   myPort.write('4'); }

    //5
   if (v1.x > 200 && v1.x < 250 ){
    println('5');
    myPort.write('5'); }

    //6
   if (v1.x > 250 && v1.x < 300 ){
    println('6');
    myPort.write('6'); }

}

Can you make the LED light up manually? That is, write simpler code that just turns that LED on and nothing else.

Your problem lies in the position of the closing bracket of the first if statement for LED 6:
//6
if(incomingByte=='1'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();         // here the closing bracket is missing
if(incomingByte=='2'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[5] = CRGB(255, 0, 0);
  FastLED.show();}

} // this is the missing closing bracket
  }
}

This means, that this whole block will only be executed, when incomingByte has the value '1'. This also means, that the last if statement will never be executed. Correct the position of the marked closing bracket and it should work.

Besides that, your code is a very complicated way of doing this. Why not simply switching the incomingByte? Also, to write less code and making it more understandable, use a function to turn all LEDs to off ("resetting" them):
void reset_LEDs(){
    for(int i=0;i<NUM_LEDS;i++){
        leds[i] = 0;
    }
}

void loop(){
if (Serial.available() > 0) {
    int incomingByte = Serial.read();

    switch(incomingByte){
        case '1':
            reset_LEDs();
            leds[0] = CRGB(255, 0, 0);
            break;
        case '2':
            reset_LEDs();
            leds[1] = CRGB(255, 0, 0);
            break;
        ...
    }
    FastLED.show();
}
}

When you stay with such easy conditions, you can even optimize more:
int incomingByte = Serial.read() - '0'; //Convert ASCII character value to decimal int value, by subtracting the ASCII value of zero
if(incomingByte > 0 && incomingByte <= NUM_LEDS){ //Test, if the incomingByte lies between 1 and NUM_LEDS including
    reset_LEDs();
    leds[incomingByte - 1] = CRGB(255, 0, 0); // -1 because array counting starts with 0, we start counting with 1
    FastLED.show();
}

For both versions, you save time, because you we only call `FastLED.show()´ once, when a change happens, not multiple times.

Thank you for this!

If this answers your question, you can accept it as correct. Thanks


text:
Usbasp Arduino Uno Bootloader Flash Error - Win 10
I'm trying to flash an Arduino Uno using usbasp but i'm getting the following error,I have checked all the connection and voltage using multimeter but still this error:
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/bin/avrdude -CC:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I have tried different three other Usbasp but still same error

This is the same dead programmer from before? Check the traces and connections on the programmer for shorts / open circuits. Also the cable.

@Majenko It's the dead programmer form before. I am using desktop with Intel Coffee Lake processor and MSI Z370 motherboard, can this cause any problem?

Take it out of the lake of coffee? Your computer is irrelevant. The fact that you have a known dead programmer is all that matters.

@Majenko Thanks

@Majenko i just need to flash the boot loader on an arduino uno, this time i'm using Arduino as ISP and getting this https://pastebin.com/3FhQfA6R, Connection: IMG1 IMG2

I have tried two different arduinos as isp but same error.

You have nothing to prevent the Nano resetting when avrdude opens the serial port...?

What i have to do to use the arduino nano to burn the boot-loader on the UNO?

Stop it from resetting. Have you read any of the (good) tutorials?

Can you share me a link of good tutorial to understand fully?

https://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers

@Majenko I have tried different three other Usbasp but still same error

The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.

I ran into the same issue. Those clone chips cannot be flashed over the ISP port. So you cannot change the bootloader at all. Just a piece of junk in my opinion.

source: Stack Exchange

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

sort: votes


text:
3-instruction remote machine coding Arduino Atmel chip over a serial line from a tethered (host) PC
I'm trying to write a program for AVR Atmel 328 chip on Arduino Nano board that will allow me to send machine code instructions to the chip over a serial line, run/execute them on the chip, and interrogate the results by reading chip memory and sending the contents back over the serial line.  This is the genesis of the idea: 3-instruction Forth by Frank Sergeant.
The remote-store and remote-fetch instructions appear to be working fine, but I've not been able to get the remote-call instruction (XCALL() function) to work. The approach I've taken is to coerce a 16-bit address into a subroutine by casting it as a function pointer.
Below is the code that is running on the Arduino Nano (compiled in the Arduino IDE and uploaded using the USB cable via the bootloader)
Any insight would be greatly appreciated!  (I can add diassembled code, my remote instructions etc, if that helps).
Thanks in advance!
// Remote serial development platform for machine coding ArduinoNano/ATmel328, AKE, Jun 9, 2020

// global variables
unsigned char byt;                  // command token from host
unsigned char mem[255];             // memory window under programmatic control
unsigned char dat;                  // data byte from host
unsigned char adr_lo;               // address from host, low byte first
unsigned char adr_hi;
unsigned short adr;                 // combined 16-bit address
typedef void (*GeneralFunction)();  // template to call memory address (as a subroutine)

void setup() {
  Serial.begin(9600);              // Turn UART serial protocol ON for comms with host PC
  Serial.write(0xFF);              // magic number to verify transmission
  Serial.write(0xFE);
  Serial.write((int) mem);         // Informs you of the writeable address space available (LSB, MSB) for tethered memory access
  Serial.write((int) mem>>8);
}

char get_byte(void) {
    while (!(Serial.available()>0)) { delay(50); }
    return Serial.read();
}
short get_adr(void) {
    adr_lo=get_byte();
    adr_hi=get_byte();
    return ( (short)adr_hi<<8 )   |   (short)adr_lo;
}
void xstore() {             // Instruction 1 = xstore(data,adr_lo,adr_hi).  Store byte from host at indicated address in target.
    dat=get_byte();
    adr=get_adr();
    *(char *)adr=dat;
}
void xfetch() {             //  Instruction 2 = xfetch(adr_lo,adr_hi).  Read byte from target memory and return to host.
        adr=get_adr();
        dat=*(char *)adr;
        Serial.write(dat);
}
void xcall() {              //  Instruction 3 = xcall(adr_lo,adr_hi).  Execute subroutine in target memory from indicated address.
                            //  WARNING!  User must have stored RET instruction to send control back to serial monitor.
        adr=get_adr();
        GeneralFunction fGf=adr;
        fGf;
}

void loop() {
    byt = get_byte();               // user specified instruction token (1,2,3)
    if(byt == 0x01 )      { xstore(); }
    else if (byt == 0x02) { xfetch(); }
    else if (byt == 0x3 ) { xcall(); } // else ignore any other serial inputs
}

AVR chips use a so called “Harvard architecture”. A Web search for those terms should provide you some insight.

Thanks Edgar.  Are you suggesting separation of program and data memory is the reason why the xcall() function as written does not work?    I would have expected the use of function pointer to allow the C compiler to map to the correct assembly instruction to access the program memory (in Flash), i.e. agnostic to whether the chip has Harvard or von Neumann architecture.

The AVR is incapable of executing instructions from RAM. There is no physical pathway from the RAM to the CPU instruction decoder. It can only execute from flash. You would have to use code executing from the bootloader area (there are some bootloaders that provide that facility) to erase a page of flash then write the code into there. Or switch to a more capable MCU that can execute from RAM.

have you seen this? ... https://arduino-forth.com/

I'd heard about FlashForth, but this collection of articles by Marc Petremann (veteran Forth coder) is excellently written and should make it a snap to get started.  Thanks for sharing the link.

The AVR CPU cannot execute instructions from RAM. It's not a question of what the compiler can do or should be able to do, the physical chip itself cannot do it. There is simply no physical pathway between the RAM and the instruction decoder in the CPU.
Instructions can only be executed directly from Flash memory. That is how the chip works. You can only execute code that you send over serial if you first erase a page (or more) of Flash memory then burn the incoming code into that page. You can then call the start of that page's address and your code will execute.
But there is another caveat there: only code running in the bootloader flash area is allowed to modify the flash memory. That means your code can't do it, only the bootloader. That doesn't mean that the bootloader has to be running, but the code that you execute has to reside there.
There is an alternative version of the Optiboot bootloader that can provide flash writing facilities to a user program, but I have no experience using it so can't assist with that.

I see! so the reason why xstore() and xfetch() worked was because I was injecting code into the mem[255] array, which is able to hold and return values as it is created in RAM.  But as it is unavailable to the Program Counter, this clears up why the xcall did not compile and the observation that the disassembled ELF file seemed to skip over the fGf() call.  Thanks much - accepting your answer!

For completeness, here's the link to Optiboot bootloader, and the MiniCore version for ATmega328.

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


text:
How can I connect nodemcu with laptop wifi
Question is odd, but I want to know that how I connect nodmcu with a laptop wifi without using any router. Is it possible if yes then how?

Configure and activate the access point mode on NodeMCU. It creates a WiFi network and you can connect to this network with your computer.

@HasnainRaza, did this help? if yes accept the answer to mark the question solved


text:
How to convert byte array into a single variable
In this code i am taking the TID data(20bytes of 160bits) in the form of array according documentation and and its working correctly and getting the output of RFID tags.
Now I just need your guidance that how can i convert the array of 20 Bytes into a single variable or into a double long datatype? or another. Because I have to push it on to my MySQL database server for further processing.
I had tried the following code which works fine
byte x[10] = "450210921";
long result = atol(x);
Serial.print("long value of the byte is: ");
Serial.println(result);

but when i put the above code into my main code, getting not any error and I am not getting the required output.!
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  byte tidLength = sizeof(myTID);

  //Read unique ID of tag
  response = nano.readTID(myTID, tidLength);
  if (response == RESPONSE_SUCCESS)
  {
    for(byte x = 0 ; x < tidLength ; x++)
    {
      if(myTID[x] < 0x10) Serial.print("0");
      /*temp[x]=(myTID[x], HEX);*/
      //Swapping values into temp variable
      temp[x]=myTID[x];
      Serial.print(temp[x]);
    }
    /*byte x[10] = "450210921";*/
    //Convert a whole array into a single long variable
    long result = atol(temp);
    Serial.print("long value of the byte is: ");
    Serial.println(result);
  }
  else
    Serial.println("Failed read");
}

There is no such thing as a single variable that is 160 bits in size.  I think you want to format the bytes as a string (and there are plenty of questions about that on here).

Ok @Majenko but is there any way to push complete an array to MySQL into a single table cell using nodemcu?

I have no idea about the MySQL side of things, but you can take each byte in the array, turn it into a text representation of a hexadecimal pair, concatenate them all in a string, and use that string.

https://arduino.stackexchange.com/questions/53258/how-to-store-an-rfid-tag-number-in-a-string

There are several simple errors: 1) "atol(x)" should be "atol(tmp)", 2) but then "tmp" should be null-terminated, 3) which then implies that it is too short. And so on.

You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.
char str[sizeof(myTID) * 2 + 1];
const char* hex = "0123456789ABCDEF";
for (int i = 0; i < sizeof(myTID); i++) {
  str[i * 2] = hex[(myTID[i] >> 4)];
  str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
}
str[sizeof(str)] = 0;
Serial.println(str);

It works! Thank, what about for this
for(byte x = 0 ; x < sizeof(myTID) ; x++)
{
content.concat(String(myTID[x] < 0x10 ? " 0" : " "));
content.concat(String(myTID[x], HEX));
}
content.toUpperCase();
softSerial.print(content);

String is not good

Could you explain it that how the string is not good!!

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


text:
Unable to get output on Arduino serial communication with ESP8266 and M6E RFID reader
I am unable to get the output on NODEMCU serial. NODEMCU is connected with Arduino Uno, and Uno is connected with M6E Nano RFID reader. Currently I am unable to understand that am i doing any mistake. Please let me know if any other thing you require.
NodeMCU and M6E Nano RFID reader pin configuration with Arduino Uno
NodeMCU         UNO
Vin             Vin
GND             GND
D2              2
D3              3

Code for Arduino Uno+M6E Nano RFID Reader
#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3);

#include "SparkFun_UHF_RFID_Reader.h"
RFID nano;

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

  while (!Serial);
  Serial.println();
  Serial.println("Initializing...");
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  char str[sizeof(myTID) * 2 + 1];
  const char* hex = "0123456789ABCDEF";

  //Read unique ID of tag
  response = nano.readTID(myTID, sizeof(myTID));
  if (response == RESPONSE_SUCCESS)
  {
    for (int i = 0; i < sizeof(myTID); i++)
    {
      str[i * 2] = hex[(myTID[i] >> 4)];
      str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
      }
    str[sizeof(str)] = 0;
    Serial.println(str);
   }
  else
    Serial.println("Failed read");
}

Code for NODEMCU
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
SoftwareSerial NodeMCU(D3,D2);

void setup()
{
  Serial.begin(9600);
  NodeMCU.begin(4800);
  pinMode(D2,OUTPUT);
  pinMode(D3,INPUT);
}

void loop(){
  String str = 0;        // stores received byte

  if(NodeMCU.available())
  {
    // get byte from USB serial port
    str = Serial.read();
    NodeMCU.write(str);
  }
delay(30);
}

Unable to find where i am doing the mistake! Thanks in advance

You have not the same baud rate on both ends.
SoftwareSerial is not reliable at 115200. use 9600 baud
SoftwareSerial on esp8266 is not reliable.

remove Uno from the project and connect the reader to NodeMcu

1, 2 Worked on the same baud rate but still does not getting any output!
3. what should I have to do! that esp8266 don't fight for interrupts with WiFi.

I just already tried(remove Uno from project) but still not getting any output! Any idea?

https://arduino.stackexchange.com/questions/57224/how-to-connect-sparkfun-m6e-nano-uhf-rfid-reader-and-esp8266-nodemcu-0-1/57229#57229


text:
Capacitor Questions
I've designed a board (HAT) that uses the ATmega328P microcontroller, and I think I might have made some mistakes in the board design. The design is most like the Arduino Pro mini, but with a 5A dual channel H-bridge, running at 3.3V 16MHz, and using the Raspberry Pi as the power source.
My Board: https://github.com/cescalemodels/BaseStationHAT/tree/master/Hardware
Arduino Pro Mini: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
1) Do I have to have C3? I think it's for power stability and needs to be put next to the microcontroller, but I'm really not sure and want to eliminate it as a possibility as to which part made the board fail.
2) Do I need C2 if I'm not using the DTR Pin?
3) I assume that I don't need C13 and C10 because I'm getting power from the Pi, but can someone confirm?
If it helps, when I boot the raspberry pi, the serial port comes up, but I am totally incapable of communicating. Are there other components that I'm missing?

The 16MHz at 3.3v is the most likely candidate for failure...

Capacitors are important, but I would atleast put the mounting holes/pads on your design and then just check if it works well withouth mounting the capacitors. If possible, monitor the voltage with a scope, to see if it dips when, for example, powering on the motors. But it's unlikely that they are the cause of the failure.

Every active chip should have adequate decoupling. That is the point of C3, to provide decoupling for the MCU. It is required.
While you don't need capacitors on the output of a non-existent regulator you do need a reservoir capacitor on the power input to your board. 10uF should be adequate.
No, you don't need the DTR capacitor if DTR is not connected to anything.
All that aside, there are two fundamental flaws I can see:

The raspberry pi can only provide something like 50mA on the 3.3v supply. (Or originally anyway, it may have improved with newer versions)
The ATMega chip cannot run reliability at 16MHz from just 3.3v. 10MHz is your top limit IIRC.

I didn't see any circuit in the links (just 5 files, which may or may not have been circuits). The PI B+ and later can supply 800mA from 3.3V, and ATmega328P will run at 12MHz on 3.3V (as used on Gertboard), although this is marginal according to the data sheet.

@Milliways That's good re: the 3.3V. When the original board came out more 3.3V current was one of the many items on my list of recommendations to Eben. It seems that's the only one he took on board ...

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


text:
Do I Have to Change Internal Interrupt Setups when I Change Clock Speed?
Do I Have to Change Internal Interrupt Setups when I Change Clock Speed? The reason I ask is because I am trying to modify this code:
https://github.com/DccPlusPlus/BaseStation/blob/master/DCCpp_Uno/DCCpp_Uno.ino (Beginning at Line 289)
so that if will work on an ATmega328P-derivative board running at 3.3V and 8 MHz. I need the waveforms to be generated at the same speed, so is there anything I have to change? The original code is written for a 16 MHz uno or mega.

Yes, you will have to recalculate all the timer compare values (halve them for half the clock speed?)

Halve the values and round down: 3199 → 1599, etc.

The equation for timer period is given by the following formula, where N is the value of the prescaler, TOP is the value given by either MAX (i.e. 0xFF, 0xFFFF) or the value in register OCRnx, and f is the frequency of the I/O clock.

If you're using phase-correct or phase- and frequency-correct mode, the factor (TOP+1) in the formula above should be replaced by 2 × TOP.

It's not TOP. It's either 2 × TOP (in the phase-correct and phase-and-frequency-correct PWM modes) or TOP + 1 (in any other mode).

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


text:
Arduino mega 2560 might be dead
I was playing with Vin and a transistor when the arduino got disconnected from my pc and after a few seconds it started to smoke. It wasn't much smoke but enough to panic and disconnect everything. I waited a few minutes and then i plugged it into my pc. The power led and the 13 pin led were on but my pc couldn't recognize my device. In arduino ide i couldn't find the port and the tx and rx leds didn't blink at all. I tried to restart my px, reset arduino, i powered it with a 12v source and i got 12v out on Vin but 0 on 5V and 3V. The 13 pin doesn't want to turn off and my pc doesn't recognize it. It is not a ch arduino and it worked perfectly until i did this. I've benn searching on internet for 2 hours now about this but i still couldn't find something relevant. In device manager it sais "unknown usb device (device descriptor request failed)" and inside proprieties at device status this is written:
"Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed."
I also tried to update drivers automatically and manual but didn't work. I have no idea where that smoke came from.
Is it dead? can i do anything to make it work?

RIP Arduino....

You could always try and check that it's not just one of the voltage regulators that broke (since you have no 3.3 or 5v)

When i connect it via the usb i get 5v and 3v out.

sounds like you smoked the vin regulator, it might be replaceable, if that's worth it to you. that might not be all that's wrong either, but it could be worth a shot

You could try re-programming it with an ICSP programmer dongle. I had 2 arduinos that suddenly died. Re-programming via ICSP instead of USB port got them back to their miserable lifes :)

I have some troubleshooting steps here: Have I bricked my Arduino Uno? Problems with uploading to board
Whilst specifically written for the Uno, a lot of it applies to the Mega. Depending on what you did, the entire board may not have failed.
Many of the components are SMD (surface mounted devices) and may be difficult to replace, unless you have specialized equipment.
If you "zapped" every chip by applying a negative voltage (say) then it might not be worth it.

i powered it with a 12v source and i got 12v out on Vin but 0 on 5V
  and 3V.

The fuse or the Vin input diode or the 5V voltage regulator or all of them could be damaged.

i plugged it into my pc. The power led and the 13 pin led were on but
  my pc couldn't recognize my device.  In arduino ide i couldn't find
  the port and the tx and rx leds didn't blink at all.

The MCU could be damaged.
The USB chip is dead (Because there is no rx blinking during programming).

If you connect the arduino through USB and there was not 3.3v at the 3.3v supply rail, the 3.3v voltage regulator is dead.
You had better buy a new one or if you want to fix it to gain experience go for it.

authors: สิรภพ เพชรฤทธิ์


text:
SPI.transfer(buffer, size) does not send data from buffer
I am having trouble getting SPI.transfer(buffer, size) to work as expected.
Here is the code:
// inslude the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;

uint16_t SPI_message = 0xABCD;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode(slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.begin();

}

void loop() {

  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
  SPI.transfer(0xEF);
  SPI.transfer(&SPI_message, 2);
  SPI.endTransaction();

  delayMicroseconds(300);

}

Here is the output of logic analyzer:

As can be seen the call for SPI.Transfer(0xEF) works as expected. However SPI.transfer(&SPI_message,2) sends 0x0000 instead of 0xABCD on the bus.
What am I doing wrong?

SPI.transfer(&SPI_message,2) is destructive. The buffer is updated with the received values.

I assume this is Arduino? Can you decrease SPI clock - currently you seem to be at the limit of your logic analyser. Does it work if you split the second transfer into two 1B transfers?  --- What Mikael said is probably the reason for your issue.

@MikaelPatel But still I should be able to see 0xABCD on my MOSI line on the SPI bus? I am not trying here to read data from a variable, but I am observing signals on the line of the SPI.

Only the first time loop is executed, then SPI_message is overwritten and zeroes are sent. Try reinitialising it to 0xabcd in loop.

@domen Exactly! this is what I was overseeing! Now it works.

@MikaelPatel your comment answers my question, together with explanation from domen. If you convert it into an answer, I can accept it. Thank you both for your help!

SPI.transfer(&SPI_message,2) is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; SPI.transfer16(SPI_message).
To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.
There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].
Cheers!
Ref.

https://www.arduino.cc/en/Reference/SPITransfer
https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137


text:
Arduino not adding decimals correctly on double variable
I have encountered a strange behavior today.
I can't understand why the sequence is altered after 26.1000.
I get a number 0.0001 less than the desired value (26.2124 instead of 26.2125).
I need precision and can't get it.
Here is the code:
double _pos = 0;

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

void loop() {
  _pos += (0.1125);
  Serial.println(_pos,4);
  while (_pos >26.5) delay(1);
}

and here is the result
0.1125
0.2250
0.3375
0.4500
0.5625
0.6750
0.7875
0.9000
1.0125
1.1250
1.2375
1.3500
1.4625
1.5750
1.6875
1.8000
1.9125
2.0250
2.1375
2.2500
2.3625
2.4750
2.5875
2.7000
2.8125
2.9250
3.0375
3.1500
3.2625
3.3750
3.4875
3.6000
3.7125
3.8250
3.9375
4.0500
4.1625
4.2750
4.3875
4.5000
4.6125
4.7250
4.8375
4.9500
5.0625
5.1750
5.2875
5.4000
5.5125
5.6250
5.7375
5.8500
5.9625
6.0750
6.1875
6.3000
6.4125
6.5250
6.6375
6.7500
6.8625
6.9750
7.0875
7.2000
7.3125
7.4250
7.5375
7.6500
7.7625
7.8750
7.9875
8.1000
8.2125
8.3250
8.4375
8.5500
8.6625
8.7750
8.8875
9.0000
9.1125
9.2250
9.3375
9.4500
9.5625
9.6750
9.7875
9.9000
10.0125
10.1250
10.2375
10.3500
10.4625
10.5750
10.6875
10.8000
10.9125
11.0250
11.1375
11.2500
11.3625
11.4750
11.5875
11.7000
11.8125
11.9250
12.0375
12.1500
12.2625
12.3750
12.4875
12.6000
12.7125
12.8250
12.9375
13.0500
13.1625
13.2750
13.3875
13.5000
13.6125
13.7250
13.8375
13.9500
14.0625
14.1750
14.2875
14.4000
14.5125
14.6250
14.7375
14.8500
14.9625
15.0750
15.1875
15.3000
15.4125
15.5250
15.6375
15.7500
15.8625
15.9750
16.0875
16.2000
16.3125
16.4250
16.5375
16.6500
16.7625
16.8750
16.9875
17.1000
17.2125
17.3250
17.4375
17.5500
17.6625
17.7750
17.8875
18.0000
18.1125
18.2250
18.3375
18.4500
18.5625
18.6750
18.7875
18.9000
19.0125
19.1250
19.2375
19.3500
19.4625
19.5750
19.6875
19.8000
19.9125
20.0250
20.1375
20.2500
20.3625
20.4750
20.5875
20.7000
20.8125
20.9250
21.0375
21.1500
21.2625
21.3750
21.4875
21.6000
21.7125
21.8250
21.9375
22.0500
22.1625
22.2750
22.3875
22.5000
22.6125
22.7250
22.8375
22.9500
23.0625
23.1750
23.2875
23.4000
23.5125
23.6250
23.7375
23.8500
23.9625
24.0750
24.1875
24.3000
24.4125
24.5250
24.6375
24.7500
24.8625
24.9750
25.0875
25.2000
25.3125
25.4250
25.5375
25.6500
25.7625
25.8750
25.9875
26.1000
26.2124
26.3249
26.4374
26.5499

If you want precision it's often better to work in fixed point, that way you can be sure of the significance of the least significant bits.

I do not see any specific difference after 26.2124.
However, in your case you are using 6 digits (e.g. 26.5499). To use an unsigned long/uint32_t you can store easily 6 digits, but only using whole numbers.
However, by adding 1125 every time and dividing the result by 10,000.0 for printing you get exact results.
unsigned long _pos = 0;

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

void loop() {
  _pos += 1125;
  Serial.println((float) _pos / 10000.0,4);
  while (_pos > 265000) delay(1);
}

Thanks, I used this approach, the only problem is that numbers can be negative too (something I did not clarify on the original question).

Than remove unsigned, so you can have negative numbers.

The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.
There is no such thing as double on an 8-bit Arduino - it is only an alias for float. By using double you aren't gaining any more precision than using float.
Even double isn't perfectly precise. It's more precise than float (on systems that support double), but still far from precise.
People that care about specific levels of precision code using variables of that precision. That's called using fixed point mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that you define it to be.
Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or granularity and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use float: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.

The number 0.1125 would written in binary as 0.0001110011001100..., with
an infinite repetition of “1100”. As the float data type has only
24 bits of precision, it can obviously not represent such a number.
Instead, when you write 0.1125 in code, you get the closest
representable number, namely 0.11249999701976776123046875, which is
0.00011100110011001100110011 in binary. Note that AVR-based Arduinos do
not really support double precision: you get a float32 whether you
declare a float or a double.
Furthermore, when you keep adding this number to itself, quite often the
sum is not a representable number. Thus, in addition to the initial
rounding error in the representation of 0.1125, you get an additional
rounding error with the addition. These errors accumulate and you end up
with a value that is significantly off what you expect.
You can avoid accumulating errors by working with integers, and
converting o float only when needed:
void loop()
{
    static long count;
    count++;
    Serial.println(count * 0.1125, 4);
    while (count > 235) delay(1);
}

Note that you still get two rounding errors: in the representation of
0.1125 and in the multiplication. But at least you are not accumulating
a large number of them.

I can't understand why the sequence is altered after 26.2124.

because floats / doubles are not precise representation of their respective values.


text:
Error compiling for any board arduino ide 1.8.9
my arduino ide Until yesterday it worked properly . but today All previous projects   dont compiling and all of them have one error : Error compiling for  board
and It's no different that Which board I choose in all of board i have this error .
please help me .
image link : http://uupload.ir/files/6hjr_capture1.jpg
error : * Error while detecting libraries included by C:\Users\ali_m\AppData\Local\Temp\arduino_build_706504\sketch\timer.ino.cpp

xtensa-lx106-elf-g++: error: CreateProcess: No such file or directory
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

is it just ESP based boards that you can't compile for?

No for all of the boards this is hapen

Can you show the error for an arduino board

image link : http://uupload.ir/files/9aht_capture33.jpg

I hope this link helps you or please try a fresh install.


text:
How to send data from firebase php to arduino?
In the project I am working on

I want to send data to firebase going to arduino this specifically by
  sending an information to change the wifi

SSID
password

materials I used:

esp8266-01
arduino uno r3
firebase
web server (000webhost)

code for arduino

    #include <SoftwareSerial.h>
#include <DHT.h>;
SoftwareSerial Serial1(10, 11);
#define Trash "Trash3"
#define DHTTYPE DHT11
#define DHTPIN 2
#define TRIGGER_PIN 4
#define ECHO_PIN 3

DHT dht(DHTPIN, DHTTYPE, 11);

float humidity, temp_f;
int distance;
long duration;

String buff(64);
String getStr(128);

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  //Serial1.resetESP();
  delay(2000);
  Serial1.setTimeout(5000);

  dht.begin();
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
      ; // do nothing
  }
  Serial.println("OK, Connected to WiFi.");

  sendCommand("AT+CIPSTA?");
  //sendCommand("AT+CIPDNS_CUR?");
  sendCommand("AT+CIPSTAMAC?");

}

void loop() {

  temp_f = dht.readTemperature();
  humidity = dht.readHumidity();
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

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

  // connect to server
  if (sendCommand("AT+CIPSTART=\"TCP\",\"gg.com\",80")) {
    Serial.println("connected to Cloud");

    // build HTTP request
    getStr = "GET /upload.php?trash=";
    getStr += Trash;
    getStr += "&distance=";
    getStr += distance;
    getStr += "&temp_f=";
    getStr += temp_f;
    getStr += "&humidity=";
    getStr += humidity;
    getStr += " HTTP/1.1\r\n";
    getStr += "Host: gg.com\r\n\r\n";

    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

      // send HTTP request
      Serial.println(getStr);
      Serial1.print(getStr);

      // print HTTP response
      if (Serial1.find("+IPD,")) { // response received
        int l = Serial1.parseInt();
        while (l > 0) {
          if (Serial1.available()) {
            Serial.write(Serial1.read());
            l--;
          }
        }
        Serial.println("--------------");
      } else {
        Serial.println("no response");
      }
    } else {
      Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
  } else {
    Serial.println("Error connecting");
  }
}

bool connectWiFi() {

  if (!sendCommand("ATE0")) // echo off
    return false;
  if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
  if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;
  return sendCommand("AT+CWJAP=\"CAPSTONE\",\"capstonemis\"");
}

bool sendCommand(const char* cmd) {
  Serial.println(cmd);
  Serial1.println(cmd);
  while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
      Serial.println(buff);
      if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
        return true;
      if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
        return false;
    }
  }
}

code for firebase

<?php

require 'firebaseLib.php';
$Trash = $_GET["trash"];

$Distance = $_GET["distance"];
$Temperature = $_GET["temp_f"];
$Humidity= $_GET["humidity"];

// --- This is your Firebase URL
$baseURI = 'https://thesis1-69.firebaseio.com';
// --- Use your token from Firebase here
$token = 'gg';
// --- Here is your parameter from the http GET

$devicestatus= array('Distance' => $Distance,'Temperature' => $Temperature,'Humidity' => $Humidity);

$firebasePath = '/thesis1-69/';

$full= array($Trash => $devicestatus);

/// --- Making calls
$fb = new Firebase($baseURI, $token);
$fb -> update($firebasePath, $full);

?>

any  guide and help can help me a lot
thank you so much :)

this is code from my chat with Xiaomy https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

yeah I am xiaomy

@Juraj can we create a chat?

why as new user?

I can't reply on the conversation and can't post new question in the recent account

we made an error in this code. change String buff(64); String getStr(128); to String buff; String getStr; and add  buff.reserve(64);  getStr.reserve(256); as first in setup()

no need to add some code on the PHP?

is this right sir?
void setup() {
buff.reserve(64);
getStr.reserve(256);
Serial.begin(9600);

I just wanna change the wifi through POST so I want to used it
I will send data to firebase then will received by the arduino

good morning sir
thank you sir
can you provide me an example of receiving the information back to arduino
I just want to change the SSID & password of arduino (esp-01) by using an app
that app uses the firebase to send data to web server back to arduino
so the wifi will be change
then no need to manually code it by using arduino IDE

it would be better to return the new ssid and password as a response of the existing request, which sends sensor data. of course only if the wifi should reconnect

so I will use the POST?

POST request is different from GET request only in one thing: it can send data in the 'body'. as you can see in my answer the data send are not in the URL, but after the request header. the response format is same for GET and POST

ah sorry about that
thank you for the right idea sir :)
but how can I get what I want?

so it will be depending on the arduino code or firebase php?

first in php add the response if the ssid should change. the Arduino sketch as it is  now prints the received response. then you can ask how to parse and process it

so likely GET request too?

I just thought to make a variable but I don't know how the firebase data will be receive by the web server

add a response to the GET request which delivers the sensor data

same format with the trash?

the GET request you have, can return the new ssid and password

I'll set 2 variables?
I don't know how can I make it
because GET request is used by the arduino to send data from web server to firebase to app

and the new ssid should be retrieved from somewhere else? not over the php page?

the app is connected to firebase
so the firebase will received the ssid and password
set by the user that use the app

I think php page will be a gateway between the arduino and firebase

so the php page can return the new ssid and password as a response to the GET request it received with the sensor data.

yes sir
I think

Comments are not for extended discussion; this conversation has been moved to chat.

add global variable String data; and in loop()
data = "trash=";
data += Trash;
data += "&distance=";
data += distance;
data += "&temp_f=";
data += temp_f;
data += "&humidity=";
data += humidity;

// build HTTP request
getStr = "POST /upload.php HTTP/1.1\r\n";
getStr += "Content-type: application/x-www-form-urlencoded\r\n";
getStr += "Content-length: ";
getStr += data.length();
getStr += "\r\nHost: gg.com\r\n\r\n";
getStr += data;

Thank you sir
so the data, it represents SSID and password?

I wanna keep both the GET and POST

for example
I will set variable namely data1 and data2
then on the
return sendCommand("AT+CWJAP="CAPSTONE","capstonemis"");
}
will be replace
return sendCommand("AT+CWJAP="data1","data2"");
}
is this right sir?

I don't need to add some PHP code on the website server?

so you want to "get" data. why do you want to do it with a "post" request?

ah it doesn't need a "post" request to get data from firebase/web server?
I got the wrong idea on using "post"
I thought it was for receiving data from firebase to arduino
I will change the wifi of arduino (esp8266-01) by using an app
that app send data to firebase then it will send data(SSID & password) to arduino


text:
How to control motor in trapezoidal manner using arduino
I am Working on a project in that i have to control motor in a Trapezoidal motion profile. on Y-axis is the velocity and X- axis as a time.
Velocity increases linearly for a certain time, then constant velocity for certain time and then Linearly decreasing the velocity and stop the motor

What kind of motor? Step motor? DC brushed? Does it have an optical encoder? How much non-linearity can you tolerate on the acceleration profile?

It is a BLDC motor, With 3000 PPR Optical Encoder. And i just want a trapezoidal motion, after that i can tweak accordingly

Hint: Start by trying to write this from an API point of view. What library function(s) are you looking for? How would you like to express this in a sketch?


text:
HTTP and HTTPS server at the same time
I'm trying to set up a HTTP and HTTPS server at the same time on an ESP8266 NodeMCU V3. The compiler however doesn't accept any other name than client otherwise no new clients will be catched. But client cannot be used twice and I cannot get it to switch every loop because of the different data-type; WiFiClient and WiFiClientSecure.
Is what I'm trying to accomplish even possible?
Sketch.ino

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_HTTPPORT  = 80;
const int   CONFIG_HTTPSPORT = 443;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <ESP8266WiFi.h>

// Create webserver object
WiFiServer HTTPserver(CONFIG_HTTPPORT);
WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
static const uint8_t rsakey[] PROGMEM = {
  #include "key.h"
};
static const uint8_t x509[] PROGMEM = {
  #include "x509.h"
};

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

  // Print WiFi connection information
  Serial.print("  MAC Address: ");
  Serial.println(WiFi.macAddress());
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Gateway: ");
  Serial.println(WiFi.gatewayIP());

  // Start webserver
  Serial.println("Starting webserver...");
  HTTPserver.begin();
  HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
  HTTPSserver.begin();
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Hostname: ");
  Serial.println(WiFi.hostname());
  Serial.print("  HTTP Port: ");
  Serial.println(CONFIG_HTTPPORT);
  Serial.print("  HTTPS Port: ");
  Serial.println(CONFIG_HTTPSPORT);

}

// Loop instructions
void loop() {

  // Wait for new client
  WiFiClient HTTPclient = HTTPserver.available();
  WiFiClientSecure HTTPSclient = HTTPSserver.available();
  if (HTTPclient || HTTPSclient) {
  }

}

UPDATE (2019-06-05):
I've tried @KIIV's method which works! However it brings a new problem into the equation. HTTPS requests take pretty long te complete, currently about 2 seconds. And it makes the HTTPS request twice for some reason (see log; I made only one request after setup).
Sketch-updated.ino

// Configuration
const char* CONFIG_SSID      = "mywifi";
const char* CONFIG_PSK       = "wifipassword";
const int   CONFIG_SERIAL    = 115200;
const int   CONFIG_HTTPPORT  = 80;
const int   CONFIG_HTTPSPORT = 443;

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

// Include libraries
#include <ESP8266WiFi.h>

// Create webserver object
WiFiServer HTTPserver(CONFIG_HTTPPORT);
WiFiServerSecure HTTPSserver(CONFIG_HTTPSPORT);
static const uint8_t rsakey[] PROGMEM = {
  #include "key.h"
};
static const uint8_t x509[] PROGMEM = {
  #include "x509.h"
};

// Setup instructions
void setup() {

  // Start serial and LED
  Serial.begin(CONFIG_SERIAL);
  Serial.println();
  Serial.println("Starting setup");
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 1);

  // Start WiFi connection
  Serial.print("Connecting to: ");
  Serial.println(CONFIG_SSID);
  WiFi.mode(WIFI_STA);
  WiFi.begin(CONFIG_SSID, CONFIG_PSK);

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

  // Print WiFi connection information
  Serial.print("  MAC Address: ");
  Serial.println(WiFi.macAddress());
  Serial.print("  SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("  RSSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
  Serial.print("  IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.print("  Gateway: ");
  Serial.println(WiFi.gatewayIP());

  // Start webserver
  Serial.println("Starting webserver...");
  HTTPserver.begin();
  HTTPSserver.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
  HTTPSserver.begin();
  Serial.println("Webserver started!");

  // Print webserver information
  Serial.print("  Hostname: ");
  Serial.println(WiFi.hostname());
  Serial.print("  HTTP Port: ");
  Serial.println(CONFIG_HTTPPORT);
  Serial.print("  HTTPS Port: ");
  Serial.println(CONFIG_HTTPSPORT);

  // Setup complete
  Serial.println("Setup completed");
  digitalWrite(LED_BUILTIN, 0);
  Serial.println();

}

// Loop instructions
void loop() {

  // New wait for new client
  if (HTTPserver.hasClient()) {

    // Set client to HTTP for this loop
    //auto client = HTTPserver.available();
    WiFiClient client = HTTPserver.available();

    // Response
    Serial.println("This is HTTP");
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/plain");
    client.println("Connection: close");
    client.println();
    client.println("This is HTTP");

  } else if (HTTPSserver.hasClient()) {

    // Set client to HTTP for this loop
    //auto client = HTTPSserver.available();
    WiFiClientSecure client = HTTPSserver.available();

    // Response
    Serial.println("This is HTTP Secure");
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/plain");
    client.println("Connection: close");
    client.println();
    client.println("This is HTTP Secure");

  }

}

Serial Log
15:59:34.121 -> Starting setup
15:59:34.121 -> Connecting to: mywifi
15:59:34.452 -> .............
15:59:38.205 -> WiFi connected!
15:59:38.205 ->   MAC Address: XX:XX:XX:XX:XX:XX
15:59:38.238 ->   SSID: mywifi
15:59:38.238 ->   RSSI: -21 dBm
15:59:38.238 ->   IP Address: 192.168.1.121
15:59:38.238 ->   Gateway: 192.168.1.1
15:59:38.238 -> Starting webserver...
15:59:38.238 -> Webserver started!
15:59:38.238 ->   Hostname: ESP_XXXXXX
15:59:38.238 ->   HTTP Port: 80
15:59:38.238 ->   HTTPS Port: 443
15:59:38.271 -> Setup completed
15:59:38.271 ->
16:00:38.069 -> This is HTTP Secure
16:00:38.833 -> This is HTTP Secure

I'd try if there is client awaiting first: if (HTTPserver.hasClient()) { auto client = HTTPSserver.available(); /* do something; */ } and the same for HTTPS. (and maybe optimistic_yield(1000) as it's used inside of available so it'll be almost the same

@KIIV your method works! It however also causes a problem; HTTPS requests take a really long time to complete. Between 5-10 seconds, which also triggers a timeout function (not present in example code). This long time is not happening when trying a sketch which only uses a HTTPS server.


text:
Send serial data at custom voltage using PWM
The Raspberry Pi has 3.3 V logic level and the Arduino has a 5V logic level.  It is warned against connecting the Arduino TX to the Pi RX:

Pi is 3.3v and the Arduino is 5v. Connect the two and you might conjure up some magic blue smoke

I was wondering if without a logic level converter chip like the CD4050, you could use the PWM functionality of the Arduino plus a low-pass-filter to effectively produce 3.3 V TX signals that would be safe for the Pi RX to receive?
I have an Arduino Uno with an ATMega8 according to the schematic.  It seems it is possible to change the frequency of the PWM pins to up to 32 kHz.  I assume it's possible to use the PWM with a low-pass-filter to effect a 3.3 V and as it runs at 32 kHz this frequency would then be more than enough to support 9600 baud rate.  Is this correct?  I'm finding it hard to search for "Arduino send serial using PWM".  The SoftwareSerial library requires any Digital IO pins so this sounds like it might not allow for using the PWM pins?  I've also read SoftwareSerial library can use the Analog Input pins for output i.e. TX?

Why the down vote?

A simple voltage divider between the Arduino TX and the Pi RX should work to protect the Pi.
And thanks to Juraj's comment, it appears that the Pi's 3.3V high will be enough to trigger the Arduino and it won't need to be boosted up to nearer 5 V.

https://arduino.stackexchange.com/questions/66170/how-does-the-dual-5v-and-3-3v-output-on-the-uno-r3-work-exactly/66180#66180

I assume it's possible to the change the value of the voltage the PWM is producing

This is not possible. PWM cannot output an analog voltage. Instead, it rapidly switches between 5 V and 0 V.

Thanks for your answer Edgar.  Could put a capacitor on it to effect a smoothing to approximate 3.3 V?

A resistor in series followed by a capacitor to ground. But that would be no simpler than a voltage divider with two resistors.

True.  I wonder why people suggest a more complex route of using the logic level converter.


text:
What is the best delay to use between characters sent to the serial port
I have an Arduino Uno. It's role is to echo back what it receives.
But if I send it a stream of ascii characters it starts to error after the first one. Occasionally it gets the second character correct but often not.
If I delay each character then it works ok. I couldn't see this limitation mentioned in the SoftwareSerial library: https://www.arduino.cc/en/Reference/SoftwareSerial
The Arduino is running the following code:
#define BT_RX_PIN 16 // A2
#define BT_TX_PIN 17 // A3
#include <SoftwareSerial.h>
SoftwareSerial OtherSerial(BT_RX_PIN, BT_TX_PIN);

void setup()
{
  Serial.begin(9600);  // not used
  OtherSerial.begin(9600);
}

void loop()
{
  if (OtherSerial.available()) {
    char value = OtherSerial.read();
    String stri = "Received: ";
    stri += value;
    OtherSerial.println(stri);
  }
}

The limitations do say "If using multiple software serial ports, only one can receive data at a time.".  I don't have multiple software serial ports though I do have an instance of the "normal" serial port but I'm not sending any data to it... but perhaps even just initialising it is enough to disrupt seamless communication with the SoftwareSerial port?
Using the following test code for serial communication from a Raspberry Pi (using logic level conversion to go from 5V -> 3.3V and visa versa):
import time

def write(msg, delay):
  for char in msg:
    with open("/dev/ttyAMA0", "w") as f:
      f.write(char)
      time.sleep(delay)

write("hello", 0.01)

I got the following results (repeated 10 times at each delay time and averaged):
Delay (ms)   |   Success rate
10           |   100 %
9            |   100 %
8            |     0 %
5            |     0 %
1            |     0 %

A delay of 9 ms between each character means the communication rate falls from ~ 960 characters per second (9600 baud / 10 bits per 7 bit character) to ~ 100 characters per second (1 / (1 / 960 characters per second + 9ms)).  Is this right?  Perhaps I'm doing something else wrong / set it up wrong in software / hardware?

Really, there is no "best delay" as it appears the delay needed depends on what the RPi sends the Arduino.  The more the RPi sends, the longer the delay in order for the Arduino to not let any data go missing.

Are you opening the serial port for every single character? Why? Should you not put the with line before the for line?

@NickGammon it was a quick hack to flush the characters to the file.

Quick hack or not, surely opening the file each character will take time?

@NickGammon ah, you mean in terms of making the "delay ms" value I have reported here actually being even longer? True. The fact we're operating in tens of ms though means it's probably not significant. * goes off to check * looks like you can open and close that file descriptor 180 times in 10 milliseconds on the hardware I'm using, about 57 microseconds.

Do you have the hardware to measure the actual delay between sends? According to my calculations you should need a longer delay: 13 * (1/960) = 13.54 ms, whereas you are saying it works with a 10 ms delay.

Fairly obviously, you will get much better throughput if you don't send the word "Received:" for each character you receive. That's like putting 13 litres of water into a bucket every second and taking 1 litre out, and then wondering why it overflows.

Thank you for your thoughts @NickGammon.  It's mainly due to the behaviour and limitations not being clearly described in the documentation that I'm on stackexchance asking for help.

The documentation should indeed make it clear that SoftwareSerial cannot receive at the same time as it is transmitting, so it is not a good choice for attempting to do that.

SoftwareSerial has a considerable overhead. It can often send at 115200 successfully but 9600 is about its limit for receiving, and you're trying both send and receive. In addition, for each character your code receives, it transmits considerably more than that 1 character (11 characters, by my count). It isn't too surprising that it would fall behind. You will need to either reduce the size of what you echo or reduce the rate at which you send characters to it (which is what you accomplished with your delay) so that the transmission (echo) rate can keep up.
Update:
The OP reports success with continuous reception by, and transmission from, the Arduino at 57600 baud (but not at the same time). The transmission rate would be consistent with my experience transmitting at 115200 baud (blindly and for short bursts, to reconfigure ESP8266-01s that were shipped with a preset 115200 rate.

13 characters because of the carriage-return/newline. This is right, you can't expect to send 13 characters for every one you receive, and keep up. Plus, when SoftwareSerial sends it turns interrupts off, so it can't receive at the same time.

@JRobert I've managed to successfully transmit continuously at 57600 baud (but with no transmit from the Arduino until after the whole message has been sent to it).  Could you edit your answer to reflect this and I'll mark it as the "correct" answer.  Thanks.

Sure - is that 57600 transmission to- or from the Arduino? Not having the direct experience, I feel I should quote yours in my update.

Yes 57600 transmission is to and from.  I tried with 115200 but (and perhaps it's due to my longer electrical wires / lack of proper grounding / interference) but this didn't work and the echo was garbage.  This could have just been the transmit from the Arduino to the Raspberry Pi but regardless in this case it didn't work at 115200 but did at 57600.

Simply put, a serial port implemented in software requires the program to sample the input pin fast enough to detect every transition.  To satisfy the Nyquist frequency rate we need the program to sample the data twice as fast as we expect the data to change.
A serial port implemented in hardware might only need to be sampled at 1/16 this rate assuming the data size is 8 bits.
Your program implements a serial port in software which is admirably keeping up with the received data.  However, when you tell the program to send the message "Received" plus the string that was received, the program stops looking at the serial input pin long enough for data to go missing.
By far the easiest solution would be to use a hardware implemented serial port.  If this is not possible consider approaching the problem using interrupts.  However, while a powerful programming tool, interrupts can be difficult to implement and hard to debug.


text:
Is it possible to use Nano with mblock and oldbootler?
I've old Nanos that to program (upload) with Arduino IDE I have to select "ATMEGA328P Old Bootloader".   The programming is via the standard Nano USB cable, and I need the CH340 driver under Windows 7.
With mblock (ide) I've selected the nano device package, but when I go to program the nano with the scratch program, the COM port is available, but the device is never found.   I suspect this is due to the old bootloader.  Is there a way to make use of the old bootloader under mblock?
[At this time not looking to re-flash my Nanos with a separate programmer.]
TIA.

"TIA" <- I hated this before I bothered looking it up. Anyway, I've never heard of this thing before. The developers section of the website seems to take me to a login screen in Chinese which isn't helpful. My only suggestion is it that if it claims to support Diecimila with 328P maybe try that. So far as I can tell they're largely compatible board definitions. If it works for you can write your own answer or someone can turn it into a community answer or whatever.

Couldn't figure out how to send makeblock the question...  But maybe new Nano's are the price I need to pay...

I'm taking the above to mean that you did not find Diecimila as an option. Re: "separate programmer". You understand that a "programmer" can be one of your Nanos, some jumpers, a breadboard, and a capacitor with the ArduinoISP sketch? So, if you're about saving money, you don't necessarily need to buy anything. Anyway, that's all I have to offer.


text:
Simple ModBus Master function 15
I have a simple setup with arduino Nano as slave and a arduino Mega as master
Can anyone explain how the function 15
FORCE_MULTIPLE_COILS
Works
i have been running some test on this
and cant figure out how to use the
local_start_address
is this the data to read from
or
is it a pointer to another File
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 1021);
dec 8 = (no_of_registers = packet->data)  // number of coils
so frame 6 = 1 (frame[6] = no_of_bytes;) // number of bytes more
dec 1021 = (packet->local_start_address)
the dec 1021 and 65565 seams to work ????
but makes no sense to me in binary format ?
Here is
part of CPP file:
enter code here

unsigned char construct_F15()
{
   // function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2;

  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
  if (packet->data % 16 > 0)
  {
    no_of_registers++;
    no_of_bytes++;
  }

  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
   unsigned int temp;

  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data

frame[index] = temp & 0xFF;

    bytes_processed++;

    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
   unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
   return frameSize;
}

this question appears to be unrelated to the Arduino

i found it
it is the
temp = register_array[packet->local_start_address + i]; // get the data
in the ccp file
register_array[packet->local_start_address + i]
its pointing to the wrong location... register_array??
supersized no one has noticed this as long as the simple modbus master for adruino
has been used ?
or i have a bad CPP file ?
i have temp corrected this by replacing with
unsigned char construct_F15()
{
    // function 15 coil information is packed LSB first until the first 8 bits are completed
    unsigned char frameSize = 10;
    unsigned char temp;
    frame[6] = 1;
    frame[7] = packet->local_start_address ^ 0XFFFF;
    return frameSize;
}

works (0 = off / 255 = on)
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 0); // 1 thru 8 = off
modbus_construct(&packets[PACKET2], 1, 15, 1, 8, 255); // 1 thru 8 = on


text:
Arduino Due: Measuring the time between pulses
I have a 'pulse train' generated from a photo interrupter and slotted disc mounted on a rotating shaft. My goal is to measure the time between each rising edge.
I have looked at the data sheet for the SAM3X8E and figured out that I need to configure a timer in 'capture mode' to do this.
My problem is that I am new to Arduino Due / this level of programming so I do not know how to set-up all the prerequisites before this (PIO, PMC, SYSCLK? etc.)
I have spent an extensive period trying to find help/ example code to no avail. Anything I do find is on Arduino Uno or Mega and therefore is of little help because of the different architecture.
Can anyone help or has anyone else done this/ similar problem?
(I am using Atmel Studio 7 as it seems to be the go-to for advanced SAM3X8E programming)
Thanks

As far as I know, there is no problem in using the Arduino IDE with the due, even for "advanced" code. The attacheInterrupt method should work like it does for the Mega or UNO. Starting a counter/timer should also be possible. Perhaps you can use the following  link as a start point. (The conversation starts with a discussion about possible counter speeds but after that, they show code for  capturing two signals and measure the time between them. If I understood by a quick look at it). I would suggest to use the Arduino IDE if possible.

what link sorry?

Wow, that's strange. Sorry, the link was removed. How can that happen? I answered the question on another computer and perhaps the link is still in the history of the browser. But, please be patient until I have access to this computer. In about ten hours. Here is another interesting link: https://forum.arduino.cc/index.php?topic=45926.0 They work with the rising and falling edges of a signal pin. Your problem is not far away from theirs. You only need the rising edge, Then read the actual time in the interrupt handler and compute the difference or mean value into a global variable.

The Firefox history does not forget ;-). Here is the link https://forum.arduino.cc/index.php?topic=400516.0 . But I had a second look into it and now I think the link from my last comment fits much better with what you want achieve.

Peter, thanks you for your response, I actually managed to find a library which seems to do the trick!

Andrew, you're welcome. Would you be so kind and add an answer with your solution and mark it as the correct answer. An unanswered question must be reviewed by the members and create some effort and perhaps there are other people having the same problem. It would be nice if they have also a link to that library. Thank you.


text:
How do I implement a userspace bootloader on Arduino Due?
Is it possible to use a custom bootloader, that loads and executes a main program stored for example on an SD card? The idea is to make it possible to update the Arduino remotely.
I tried this with a bootloader, which writes the program into the flash storage with a 32KB offset and then uses a function pointer with that address (0x88000) to continue execution there. The 0x80000 is as far as I am informed the address offset of the flash storage. It can be written on Due boards with this library: https://github.com/sebnil/DueFlashStorage. The problem was that this just hasn't worked, the Arduino simply stopped responding after the function pointer being executed. I would appreciate any information or hints on this topic.

A solution of this type should be possible - but was your loaded program linked to execute at that address?  And did you come up with a scheme for handling interrupt vectors?  I believe on the ARM cortex you can change the address of the vector table.

The guys at Phoenard did just that with an AVR2560. They wrote a bootloader that loads and saves FLASH memory from/to the Micro-SD card. You can save HEX files on an SD card and then load one of them in the FLASH memory and run it.

Not sure if you could get the bootloader to support SD, but I have little experience with bootloader code, so the way I would go about it would be to make the sketch load content from the SD that then affects the sketch process.

That sounds like what the poster already did.  To be an answer, this would need to provide a path around the fact that it didn't work - by being more than just a vague idea.


text:
How to have an Arduino communicate with 3 other Arduinos?
I was wondering how I can get 4 Arduinos in total to communicate with each-other through a wired connection. The goal is to have the master Arduino send a number 0-100 to each of the other Arduinos.
The master unit will be an Arduino Uno and the other 3 Arduinos will be Arduino Pro Minis.

There are lots of ways. You're going to need to be more specific about your requirements.

how to communicate multiple ardunio wirelessly??

@SHAUKATALIKHAN  lookup NRF24L01 with radionics

You could use: U(S)ART, I²C or SPI. You should check this post for information on these protocols.
Some quick googling gave me this:

SPI: mainly for high data rates, approx 25 MHz clock but only bus has to be on same voltage level, single master (can be done through software), data arbitration not possible.
I2C: mainly for control and low data transfer (limited by bus capacity, etc...), but can be interfaced to different voltage levels and multimaster bus environment, inbuilt arbitration etc...
UART: single P2P comm, 115 kbps max.

http://www.edaboard.com/thread53139.html
I don't fully agree with it. You can send via UART to multiple devices, but then you have to handle the addressing in software. But other than that, UART is very easy to debug as Arduinos often have an USB connection.
"I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use". I don't yet have a lot of experience with this protocol, but if you want to use it, check out the other answer.
SPI would be a fair shot as it does enable master with multiple slaves in its standard.
Summary:
All protocols have different pros and cons. It's not really up to us to choose one for you. And you should look them up and learn about them by yourself.
Then try to choose which one applies most to your needs, and get started with that protocol. They are well documented and if you really can't get out of it, you can post another question ;D

I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use: only two wires and no need to match port configurations (baudrate, parity, stop bit(s)...).

Ah, I see, haven't yet used I²C with arduino, but for a beginner, but in general it's better to know the hardware before you start on the software. In this way you know what to do and how to debug it. But I can imagine that arduino has steady/easy libraries for this. But same is for setting up serial connection in arduino?

UARTs don't need to be single P2P; AVRs do support a form of multiple slave using a 9-bit protocol.

I also said that in the 3rd 'paragraph', though adressing isn't standard in the uart protocol? Or well you will have to handle it software. With SPI you simply have a slave select pin that selects which slave to talk to.
I didn't know that 9-bit protocol is for adressing? Or well I don't believe it's defined so in the standard? But yes, an extra bit could help.
You could also send one byte with the address/setting and then send (an)other byte(s) with the message. Then on each slave you should check the first byte, and only handle the second when neccesary.

I agree knowing the physical layer can help, but for using I²C you only need to know that addresses and data are multiplexed on the same lines, which simplifies the cabling (only 2 wires). On the software side, it's really simple: see the Master Writer/Slave Receiver Arduino tutorial, which can be trivially expanded to many slaves just by using different slave addresses.

You can use the I2C communication protocol through the wire.h library. That will permit you to use the arduino uno as master device and the pro minis as slave.
Briefly, you use a two wire's connected to the SDA and SCL pins of all the arduino board and then the master to interact ( meaning request data and send data) with the slaves uses there address (that is user defined in the slave software). So the normal routine in I2C goes like this:

The master sends the address plus the read write instruction on the bus.
All the arduino boards listen and if the address matches with there internal adress they perform the instruction.
If it is write command from the master the slaves prepare to receive. If it is read command from the master, the master waits until the slave send a byte.

Fr more information go on:
Arduino two wire communication
I2C official datasheet

You can use RS-485 connection between all arduinos using serial port of all. For a half duplex connection for 4 arduinos, the setup can be like this:
What Do You Need:

4 RS-485 line drivers (like max485). One for each arduino
if the distance between arduinos are short (under 1 mt) these will br enough
if the distance between arduinos are long (over 2mt) you'll need to use at least 24 AWG twisted pair cable between them and 2 120 ohm resistors. These resistors will be line terminators.
You can check max485 datasheet to see how to connect them

Setting Up:
To use rs485 with arduino and half duplex, you'll need 3 pins. 2 pins for rx and tx. 1 pin for transmit-enable. In half duplex mode, normally all nodes are in listening mode. To configure transmit enable, connect "drive enable" and "receive enable" pins of rs485 driver together. This will be our "transmit-enable" pin.
Connection:
      |        |
c  RX |------->|RO     4
p  TX |------->|DI     8
u D13 |------->|TE&RE^ 5
      |        |

Software:
Download this library (Mertbus). This library implements a basic transport layer. It is in alpha stage but functional. There is sample code in it and also a .net library.
The logic is similar to TCP/IP. Give every node an address between 0 and 126. 127 is the broadcast id. Means if you send data to id 127 all nodes will receive it. If you send data to only one node (ex. 2 ...) only target node will receive.
Sample:
#include "MertBus.h" //include header

#define TXEN 13  //transmit-enable pin
#define SELF_ID 1  //id of this node

MertBus mb;  //communicator class

void setup() {
   Serial.begin(57600); //prepare the serial port as usual
   Serial.println("Begin init");
   //then initialize mertbus instance with port, pin and id
   mb = MertBus(Serial,TXEN,SELF_ID);
}

void loop() {
  if(mb.checkData()) {    //check if and valid data received
    // reply to sender char[] and length, 26 chars
    mb.reply("Incoming Data (SendData): ",26);
    // reply to sender the received data
    mb.reply(mb.Buffer,mb.ReceiveCount);
  } else {
    digitalWrite(13,HIGH);
    delay(400);
    digitalWrite(13,LOW);
    delay(400);
  }
}

To be a master, to send data (without replying to a message, starting a new one):
//buffer data to send, to_addr is target node address
//buffer_size is the size of data to send.
mb.sendData(char * buffer, uint8_t to_addr, uint8_t buffer_size)

If they are reasonably close to each other, by far the simplest would be to use serial comms, since you say you want to send a number (but do not mention receiving anything).
You could have the Tx pin on the master Arduino connected to the Rx pin of all the other Arduinos (plus a ground connection of course). Then send your numbers to your heart's delight. I suggest some sort of protocol like:
(42)

Where the opening and closing braces indicate to the receiver where the number starts and ends. If the distance is more than (say) 5 meters, an RS485 transceiver may be called for at each end, eg.

I have a description of the sort of thing on my RS485 communications page.
You can "drop" multiple transceivers off the same pair of cables.
RS485 is reasonably resistant to line noise because it is a balanced protocol.
These transceivers can transmit or receive but not at the same time. In your case you would have the master with Tx Enable active, and the slaves the Tx Enable not active.
If the chips are dropped off a long cable run you should have a termination resistor between A and /B at the end (say, 120 Ω).
SPI could be OK, but is really for short runs. I2C could be OK too, but may be unnecessarily complex. However if you go with I2C it does have a "broadcast" mode which might suit sending the same thing to multiple devices.

References

RS485 communications
RS485 - Wikipedia
I2C (Wire)
SPI
Async serial

Nick, what did you use to generate those circuit diagrams?

ExpressSCH from expresspcb.com. It's free software for Windows that draws schematics and PCBs. It's simple to use (which is why I like it). It has a library of major parts, plus you can make your own out of boxes and lines.

PJON is a bit banged serial bus protocol for multiple nodes. You may find it useful.

PJON™ (Padded Jittering Operative Network) is an Arduino compatible,
  multi-master, multi-media communications bus system. It proposes a
  Standard, it is designed as a framework and implements a totally
  software emulated network protocol stack that can be easily
  cross-compiled on many architectures like ATtiny, ATmega, ESP8266,
  Teensy, Raspberry Pi, Linux and Windows x86 machines. It is a valid
  tool to quickly and comprehensibly build a network of devices


text:
Arduino with OV7670 - a buffer
I have an Arduino UNO and OV7670 camera sensor without FIFO. I wanted to build a device, that would take frame once in a while, and would send it through bluetooth (HC-05) or wi-fi (esp-01). I didn't know though, that the microcontroller inside Uno has so little RAM memory, that the frame doesn't fit inside. Moreover, even Arduino Mega has too little memory...
My question is- is there anything I could do to take a VGA-resolution photo (circa 1MB) and send it through any serial medium?
I suppose it'd be some kind of a buffer or memory- I'm asking for references to concrete chips or solutions (like- would it be possible to encode or compress an image on-the-fly)?

The first thing you could do is but the camera with the buffer :)
The ESP-01 has much more RAM than the Arduino, I don't think its got enough still though.
You can buy the FIFO chip that the other version of the camera uses, you could try and retro fit your camera.

Oh. Looks like ESP-01 could have enough memory for grayscale or lower resolution frame. It's surprising to find that I could do without Arduino...
By 'retrofitting' you mean adding the FIFO manually to the camera circuit? It sounds like a pretty difficult process...

I have a camera with FIFO, one without and a couple of FIFO memory chips.  I wasn't sure if I could either attach the FIFO to the camera (I agree sounds horrid) or use the FIFO from the ESP.  But then I got distracted and its at the bottom of a heap of electronics somewhere.  So I can't tell you which way to go, just offer suggestions.  To be honest though, buying a camera with FIFO might be a lot less hassle.

Compress on the already belabored Uno/Mega? Nope. If you're okay with grayscale, you don't need 1 MB buffer space. With the YCbCr422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.

if it's not a silly question, does the entire image need to be sent in a single transaction? i believe with i2c you could issue the command to capture, and then read back chunks at a time (that fit within your RAM) send those chunks, then repeat until no image data left to retrieve?

@JamesKent thing is, theres no command to capture. Once the camera is powered and an clock signal is applied, it begins spitting out frames on its signal lines, with the frame rate and time between bytes determined by the applied clock. Frames arent packetized and cant be requested for at leisure. You're either there to capture them or you arent.

Sorry, i misunderstood, what about stopping the clock to the camera periodically?

@JamesKent I'm not sure but if you stop the clock in the middle of a frame, you'll probably lose the rest of that frame's data. The camera needs the clock to function; won't even respond to commands over I2C.

If you're okay with grayscale, you don't need 1 MB buffer space. With the YUV422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.
However, according to this, you can set the hardware serial baud rate to 1M-baud and transmit the image bytes as you receive them without buffering. main() shows how to set up the serial port and you can also see how they received each VGA pixel byte in Bayer-RGB and transmitted immediately; notice that all interrupts are disabled first, given the high-speed nature of the transfer. But instead of Bayer, I'd recommend you use YUV422 instead, meaning the camera sends 2 bytes per pixel. Because you're only interested in the Y byte, you can place that in the UART buffer and use the time spent in receiving (and discarding) the second U/V byte to give the UART peripheral some additional breathing room to send the Y byte, before you send the next one.
Regarding the high baud rate, the crystal frequency of the Arduino doesn't matter so much because you'll only be transmitting to your PC, which should be able to handle the speed even given the rate error. Note that in main(), double speed async is enabled, and UBRR is set to 500 kBaud to obtain 1-Mbaud. Also notice that an 8MHz PWM signal was used to clock the camera (XCLK signal) with no PLLs activated in the camera register settings. This is another tutorial related to the same code; may clear up a few things.
If you really want to use a chip solution, you can look up parallel SRAM like the HM628128; it's only 128kB though, you'll need to find a bigger one to hold an entire frame of 307kB. Parallel SRAM are great because you can attain really high write speeds because of the simple interface. You'll need some sort of counter connected to the SRAM address lines clocked by the PCLK line (divided by 2, since you only want every other byte) so that every pulse increments the address. This same clock will feed the nW signal to actually clock the data into the SRAM (after satisfying address setup times somehow). The camera data lines will be connected directly to the SRAM and you activate the SRAM's chip select signal based on your monitoring of the camera's VSYNC signal (to know when a new frame's about to start). When the frame's done, you read from the RAM and forward the bytes to your destination.
All this assumes you aren't trying for video, merely taking frames "once in a while". Though the first solution will work for video, albeit poor video.

You need to add a FIFO buffer to the camera, or work out a scheme for streaming data from the camera over the network, because you don't have anywhere enough memory to store the image.

authors: Олег Черников


text:
reverse 12v motor
I am working on an RC car, and I need to be able to reverse a 12v circuit that powers my main drive motor.
I have a TIP102 transistor and a 5-30v relay for each motor terminal. I assumed that I could open up ground via the transistor on one side, and the power relay on the other, and then switch these to reverse.
My motor runs each direction when hooked directly to the battery, and my relays are definitely outputting the full 12v, but I seem to have a problem with the grounding circuit. Whichever side has the relay switched on, that transistor gets very hot, and my motor doesn't spin. I tested the transistor and can get it to ground when on a single directional circuit with just the relay on one side and the TIP102 on the other.
Here is my wiring. Can anyone tell me where I screwed up?
Ignore the 9v, I just couldnt find a 12v in fritzing

You want a H-bridge motor driver. There's plenty of shields around to do it.

If the diagram correctly represents what you have, it isn't obvious to me what the problem might be.  One possibility is that the base resistors to the TIP102's are too large.  Too little current into a transistor base keeps a transistor out of saturation, ie operating in a linear mode instead of switching mode, leading to high power loss and high heat.  Slightly more likely is that the fairly high voltage drop across the Darlington in the TIP102 is just heating it up a lot.
If, as suggested in a comment, you were to use an H-bridge motor driver, it might include heat sinks or might use MOSFETs with lower voltage drops; thus avoiding so much lost heat, one way or the other.
As it happens, you probably don't need the transistors in the circuit anyway.  Label the relays as A and B.  Hook one of the motor leads to the common terminal of A, and the other motor lead to the common terminal of B.  Hook the NO lead of each relay to V+, and the NC lead of each to ground.  To run one direction, switch A on and B off.  To run the other direction, switch A off and B on.  To stop, switch both off.

Brilliant! That did the trick. I followed your relay wiring and it does exactly what I wanted. Thank you.

@Broom, good deal.  Relays are fine for on-off motor control.  But if you need PWM, buy an H-bridge.  They usually have MOSFETs (reducing heat) and protective diodes (to keep inductive voltage kick from destroying transistors).

authors: Владимир Дубов


text:
Arduino powered car not running when touching ground
I hacked a cheap car I connected both motors to L298N Dual H-Bridge Motor Controller and all things are working good. Motors are running fast. But when I put the car on the ground to run. It runs so slow. I am using 4.5V for L298N.
What can I do to run it fast on ground?
I have tried PWM but it does not work.
What can be the causes of this?

Some measurements could help understand the issue.

What are you using to provide the 4.5volt?

The car's default battery back. It has space for 3 1.5V batteries. I am using that.


text:
Arduino serial port implementation
It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.
From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.
Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.

It depends on which Arduino and which serial port you are talking about. It can be a raw UART (TX and RX pins), an UART tunneled through USB by another chip (e.g. in the Uno communicating with the host computer), or a completely virtual UART seen through USB (e.g. in the Leonardo).

but to answer the question, there are two separate buffers, the arduino can only read or write at a time, but the hardware side can be treated as being full duplex with separate buffers.

The AVR UART has a simple one step hardware queue for both the RX and the TX. The hardware has a register for the parallel to serial conversion and a queue register to allow write/read while a transmit/receive is in progress. The Arduino HardwareSerial class adds a software queue (32 or 64 bytes). These buffers are used to feed the hardware queues on interrupts from the UART hardware module.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?.

Yes. Arduino has two buffers. See the HardwareSerial.h and HardwareSerial.cpp

I have a lengthy post about Arduino serial communications: How does serial communications work on the Arduino?
In short, the hardware (on an Atmega328 like on the Uno) has a two-byte receive queue (so you can be putting one byte into memory while the next byte is being received). It has a one-byte send queue.
Lengthier queues are implemented in software using interrupts to move data from the RAM queues in/out of the hardware queues.


text:
I have to reload Sketch every time I start my Yun
I am new to Arduino and IoT. I got my hands on a Yun and loaded a simple sketch to subscribe to a topic. I am receiving messages (I have set up a PHP script and broker on a server, which takes care of the messages) and can turn ON and OFF LED, L13. But when I disconnect the Yun from my PC and connect it again (to power it up), it stops receiving messages. I have to load the sketch again to make it work. Here is my code:
#include <spi.h>
#include <pubsubclient.h>
#include <yunclient.h>

byte server[] = { 192, 168, 1, 196 };
int port = 1883;
char* pubTopic = "fromYun";
char* subTopic = "sensor/light";

void callback(char* topic, byte* payload, unsigned int length) {
  //convert byte to char
  payload[length] = '\0';
  String strPayload = String((char*)payload);
  // handle message arrived
  if(strPayload == "ON") {
    digitalWrite(13, HIGH);
  } else if(strPayload == "OFF") {
    digitalWrite(13, LOW);
  }
}

YunClient yun;
PubSubClient mqtt(server, port, callback, yun);

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  if (mqtt.connect("arduinoClient")) {
    mqtt.publish(pubTopic,"hello world!");
    mqtt.subscribe(subTopic);
  }
}

void loop() {
  mqtt.loop();
}

Am I missing something?
I referred to this post and PubSubClient -> mqtt_basic.ino for making this ketch.
I don't understand what mqtt.connect("arduinoClient") is. I mean, what is this string "arduinoClient"? In one sketch on GitHub I saw it as "yun"...
Any help will be appreciated. Thanks in advance!
EDIT: I am using Mosquitto MQTT.

Please explain which messages? Serial port messages or MQTT messages?
The mqtt.connect name "arduinoClient" is the ID name. It depends on the server what the parameters should be. For some servers it can be an empty string and the second parameter should be the account name, and a third parameter for the password/key.
When you upload a sketch, the OpenWrt part is already running. Perhaps there is a problem with Bridge.begin. Try to wait 90 seconds before calling Bridge.begin. If a 90-second delay makes it work, lower it to 5 seconds, and keep it at 5 seconds.
Perhaps you can use (blinking) LEDs to indicate that the code has finished the Bridge.begin or to indicate an error.
When you solve this problem, there will be other problems. Have you updated to the newest firmware for the OpenWrt part? The Arduino Yún might only work with a very simple and small sketch. Don't try to add too many things that use the Bridge. The OpenWrt/linux part is reliable, you can run linux scripts there. The ATmega32U4 part is just like an Arduino Leonardo and is also reliable. It is the combination and the Bridge that causes a never ending chain of problems.
What about the Raspberry Pi? That is reliable. Have you thought about the ESP8266 or ESP32 in Arduino compatible mode? Adafruit has an MQTT server for users, and the Adafruit Feather M0 WiFi seems a very nice board. Anything but the Yún.
My best advice for you is to grab a hammer and destroy the Yún and forget about it. It will make your life so much easier.
(I just noticed that this is a very old question, sorry, but my answer is still valid).

It's dubious to call raspberry pi's reliable when they depend on a fragile SD card for their root filesystem. Waiting for the Linux side of things to fully start up does sound like a good idea, unless part of the Linux startup is commanding a reset of the ATmega. Ultimately, to get reliable communication through a bridge likely requires doing a full handshake between the software on both sides. A better system design would probably run most of the logic on the Linux side (as you observed, "you can run scripts there") and use the ATmega only as a delegate for I/O or simple realtime sequencing.