text:
RGB LED Mode toggle - Trying to avoid using main loop()
I'd like to start by saying that I have only been dabbling in electronics (not just Arduino) for about 3 days now.
I am trying to write a sketch which changes an RGB LED when a push switch is pressed.
There are 6 modes -
0 = off
1 = dim
2 = mid brightness
3 = full brightness
4 = cycle through RGB colours
5 = pause the colour cycle at the current colour

I have managed to get this working using the code below this explanation.
What I would like to know is this -
Since the LED only changes state when the button is pressed, is it possible to avoid the use of the main 'loop()' entirely?
Will work fine for modes 0, 1, 2 and 3, but the interrupt cannot fire until mode 4 has finished 1 entire colour cycle.
/*
 * LED MODES
 * 0 = off
 * 1 = dim
 * 2 = mid
 * 3 = bright
 * 4 = colour cycle
 * 5 = colour select
 */
volatile int ledMode = 0; // off
const int maxLEDMode = 5;
volatile bool buttonPressed = false;

int rPin = 9;
int gPin = 10;
int bPin = 11;
int ledPin = 5;
int buttonPin = 2;
int currentVals[] = {0, 0, 0};

void setup() {
  Serial.begin(9600);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);
}

void loop() {
  setBrightness(); // try and move outside of main loop
}

// Ensure that buttonPress does not trigger twice
void buttonPress(){
  if(digitalRead(buttonPin) == 0){
    delay(10);
    if(digitalRead(buttonPin) == 0){

      setMode();
      buttonPressed = true;
      Serial.println(ledMode);
    }
  }
}

//Increment LED Mode until max level is reached
void setMode(){
  if(ledMode == maxLEDMode){
    ledMode = 0;
  } else {
    ledMode++;
  }
}

//Set LED colours depending on ledMode
void setBrightness(){
  buttonPressed = false;

  if(ledMode == 0){
    mode0();
  }

  if(ledMode == 1){
    mode1();
  }

  if(ledMode == 2){
    mode2();
  }

  if(ledMode == 3){
    mode3();
  }

  if(ledMode == 4){
    mode4();
  }

  if(ledMode == 5){
    mode5();
  }
}

//Fade to off
void mode0 (){
  fadeTo(0, 0, 0, 10);
}

// Fade to dim light
void mode1 (){
  int val = 255/5;
  fadeTo(val, val, val, 100);
}

// Fade to medium light
void mode2 (){
  int val = (255/3);
  fadeTo(val, val, val, 100);
}

// Fade to bright light
void mode3 (){
  fadeTo(255, 255, 255, 100);
}

// Endlessly cycle through RGB colours
void mode4(){
    fadeToWithCheck(255, 0, 0, 500);
    fadeToWithCheck(255, 255, 0, 500);
    fadeToWithCheck(0, 255, 0, 500);
    fadeToWithCheck(0, 255, 255, 500);
    fadeToWithCheck(0, 0, 255, 500);
    fadeToWithCheck(255, 0, 255, 500);
}

// Pause LED on colour inherited from Mode4
void mode5(){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];
  fadeTo(rExisting, gExisting, bExisting, 1);
}

// Fade to given colour, with awareness of mode4 toggles
void fadeToWithCheck(int r, int g, int b, int interval){
  if(ledMode == 4){
    int rExisting = currentVals[0];
    int gExisting = currentVals[1];
    int bExisting = currentVals[2];

    for(int i = 0; i <= interval; i++){
      analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
      analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
      analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));

      if(buttonPressed == true){
        Serial.println("stopping loop");
        currentVals[0] = map(i, 0, interval, rExisting, r);
        currentVals[1] = map(i, 0, interval, gExisting, g);
        currentVals[2] = map(i, 0, interval, bExisting, b);
        break;
      }
      delay(10);
    }

    if(buttonPressed == true){
      buttonPressed = false;
    } else {
      currentVals[0] = r;
      currentVals[1] = g;
      currentVals[2] = b;
    }
  }
}

// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  for(int i = 0; i <= interval; i++){
    analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
    delay(10);
  }
  currentVals[0] = r;
  currentVals[1] = g;
  currentVals[2] = b;
}

// Invert given value due to cathode/anode LED
void analogWriteInverted( byte pin, byte value)
{
  analogWrite(pin, 255-value);
}

Any help or advice at all would be appreciated!
Many thanks,
Rob
UPDATE - Working solution
Following on from the advice given by Michel, the following code meets my needs perfectly.
#include "TimerOne.h"

/*
 * LED MODES
 * 0 = off
 * 1 = dim
 * 2 = mid
 * 3 = bright
 * 4 = colour cycle
 * 5 = colour select
 */
volatile int ledMode = 0; // off
const int maxLEDMode = 5;
volatile bool buttonPressed = false;
unsigned long lastDebounceTime = -1;
unsigned long debounceDelay = 200;
int lastButtonState = HIGH;
int buttonState;
long secondTimer = 1000000;

int rPin = 6;
int gPin = 5;
int bPin = 3;
int buttonPin = 2;
int currentVals[] = {0, 0, 0};
int mode4Vals[] = {0, 0, 0};
int mode4Stage = 0;

long fadeInterval = 0;
long lastSeenInterval;

void setup() {
  Serial.begin(9600);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  Timer1.initialize(secondTimer / 1000);
  attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPress, FALLING);

  turnOff();
}

void loop() {
  //setBrightness(); // try and move outside of main loop

}

void turnOff(){
  analogWriteInverted(rPin,0);
  analogWriteInverted(gPin,0);
  analogWriteInverted(bPin,0);

  currentVals[0] = 0;
  currentVals[1] = 0;
  currentVals[2] = 0;
}

// Ensure that buttonPress does not trigger twice
void buttonPress(){
  int reading = digitalRead(buttonPin);

  if (lastDebounceTime < 0 || (millis() - lastDebounceTime) > debounceDelay) {
    lastDebounceTime = millis();
    if(ledMode != 4){
        clearTimer();
    }
        setMode();
        buttonPressed = true;
        Timer1.attachInterrupt(incrementGlobalFadeInterval);
      }
    }

//Increment LED Mode until max level is reached
void setMode(){
  if(ledMode == maxLEDMode){
    ledMode = 0;
  } else {
    ledMode++;
  }
}

//Set LED colours depending on ledMode
void setBrightness(){
  buttonPressed = false;

  switch(ledMode){
    case 0: mode0(); break;
    case 1: mode1(); break;
    case 2: mode2(); break;
    case 3: mode3(); break;
    case 4: mode4(); break;
    case 5: mode5(); break;
    default: abort();
  }

}

//Fade to off
void mode0 (){
  fadeTo(0, 0, 0, 400);
}

// Fade to dim light
void mode1 (){
  int val = 255/5;
  fadeTo(val, val, val, 50);
}

// Fade to medium light
void mode2 (){
  int val = (255/3);
  fadeTo(val, val, val, 50);
}

// Fade to bright light
void mode3 (){
  fadeTo(255, 255, 255, 50);
}

// Endlessly cycle through RGB colours
void mode4(){
  switch(mode4Stage){
    case 0: fadeToWithCheck(255, 0, 0, 2000); break;
    case 1: fadeToWithCheck(255, 255, 0, 2000); break;
    case 2: fadeToWithCheck(0, 255, 0, 2000); break;
    case 3: fadeToWithCheck(0, 255, 255, 2000); break;
    case 4: fadeToWithCheck(0, 0, 255, 2000); break;
    case 5: fadeToWithCheck(255, 0, 255, 2000); break;
    default: abort();
  }
}

// Pause LED on colour inherited from Mode4
void mode5(){
  currentVals[0] = mode4Vals[0];
  currentVals[1] = mode4Vals[1];
  currentVals[2] = mode4Vals[2];

  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];
  fadeTo(rExisting, gExisting, bExisting, 1);
}

// Fade to given colour, with awareness of mode4 toggles
void fadeToWithCheck(int r, int g, int b, int interval){
  if(ledMode == 4){
    int rExisting = currentVals[0];
    int gExisting = currentVals[1];
    int bExisting = currentVals[2];

    if(fadeInterval <= interval && lastSeenInterval != fadeInterval){
      lastSeenInterval = fadeInterval;
      analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
      analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
      analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));

      mode4Vals[0] = map(fadeInterval, 0, interval, rExisting, r);
      mode4Vals[1] = map(fadeInterval, 0, interval, gExisting, g);
      mode4Vals[2] = map(fadeInterval, 0, interval, bExisting, b);
    } else {
      currentVals[0] = map(fadeInterval, 0, interval, rExisting, r);
      currentVals[1] = map(fadeInterval, 0, interval, gExisting, g);
      currentVals[2] = map(fadeInterval, 0, interval, bExisting, b);
      fadeInterval = 0;

      if(mode4Stage == 5){
        mode4Stage = 0;
      } else {
        mode4Stage++;
      }
    }
  }
}

// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  if(fadeInterval <= interval && fadeInterval != lastSeenInterval){
    lastSeenInterval = fadeInterval;
    analogWriteInverted(rPin, map(fadeInterval, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(fadeInterval, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(fadeInterval, 0, interval, bExisting, b));
  } else {
    clearTimer();
    currentVals[0] = r;
    currentVals[1] = g;
    currentVals[2] = b;
  }
}

void incrementGlobalFadeInterval(){
  fadeInterval++;
  setBrightness();
}

void clearTimer(){
  Timer1.detachInterrupt();
  fadeInterval = 0;
  lastSeenInterval = -1;
}

// Invert given value due to cathode/anode LED
void analogWriteInverted( byte pin, byte value)
{
  analogWrite(pin, 255-value);
}

Try switch function in C++.  You'll find the info via a search engine.

I'm guessing it will perform the same way as the switch in C#. That would tidy up my  setBrightness function a lot. Good thinking! I'm not too clear on how this would avoid the use of the main loop function though?

One other problem I see is you use delay, and a delay should not be used inside an interrupt.

Thanks Michel, is this because it is not best practice or can it cause fundamental issues? I put this in place because, when I pressed the button, the ISR was triggering a random number of times, sometimes once, sometimes up to 3 times. Have you seen an issue like that before? Sorry if this should be another post entirely.

upvote for a well written post

Keep interrupt shorts
Inside an interrupt, do not use long pauses, thus not a delay. As chrisl notes below (see comment) delay does not even work inside an interrupt, since it is based on millis(), which are not updated within an interrupt.
The reason is that interrupts should be as short as possible (so even if you would use a for loop with micros() or another way to hold the execution time), because it can cause new interrupts not to be called (during an interrupt, no new interrupts will be called, at least not with the same/lower priority). So always keep code within interrupts very short, especially delay's are violating this, but also serial.print statements.
I see you use this function which will be called if you put everything in the interrupt handler:
// Fade to given colour
void fadeTo(int r, int g, int b, int interval){
  int rExisting = currentVals[0];
  int gExisting = currentVals[1];
  int bExisting = currentVals[2];

  for(int i = 0; i <= interval; i++){
    analogWriteInverted(rPin, map(i, 0, interval, rExisting, r));
    analogWriteInverted(gPin, map(i, 0, interval, gExisting, g));
    analogWriteInverted(bPin, map(i, 0, interval, bExisting, b));
    delay(10);
  }
  currentVals[0] = r;
  currentVals[1] = g;
  currentVals[2] = b;
}

Removing delays
To remove the delay, is a bit tricky though. What you need to do is (approximately):

Create a global variable instead of the loop variable (i, but give it a better name)
Calling an additional interrupt based on 10 ms (the delay).
In that interrupt, handle the next iteration (so increase the global variable i (but the new name)
Handle post processing (e.g. if i == interval, execute the last three statements of the function (and possibly other statements from called functions in the original code).

Multiple if to one switch statement
Also you can use a switch statement.. Instead of
 if(ledMode == 0){
    mode0();
  }

  if(ledMode == 1){
    mode1();
  }

  if(ledMode == 2){
    mode2();
  }

  if(ledMode == 3){
    mode3();
  }

  if(ledMode == 4){
    mode4();
  }

  if(ledMode == 5){
    mode5();
  }
}

Use
switch (ledMode)
{
case 0:
  mode0();
  break;

case 1:
  mode1();
  break;

..

case 5:
  mode5();
  break;

default:
   abort(); // Error condition
}

Since the cases are so simple I put them normally on one line:
switch (ledMode)
{
case 0: mode0(); break;
case 1: mode1(); break;
..
case 5: mode5(); break;
default: abort();
}

Button debouncing
In your remark you say after a button press, sometimes the function is called multiple times. This is caused by button bouncing. When you press a button, for a short time, the contact is somewhere between on and off. During this time, it can change a few times between on and off, thus you get multiple calls, mostly very short after each other. To prevent this, use button debouncing (check the Arduino site for a Button Debounce example). It means that you check if a certain state has been stable for some time, and than perform the action, instead of immediately.

Great answer Michel, I'm pretty sure that all makes sense to me. I will give it a go and get back to you with my findings.

Good luck, if it helps you, please consider upvoting/accepting the answer.

I thought, that delay() does not work at all inside of an ISR, because it relies on millis(), which in turn relies on interrupt for counting time.

@chrisl you are right, mostly, you can use milis(), but it is not updated, so the use of delay doesn't work indeed. I will adapt the answer. Thanks!

Thanks for the help Michel! Not sure if my solution is exactly what you imagined, but it certainly does the trick. I have updated my question with the working code.

Remove the buttonPressed = false; from fadeToWithCheck. As in mode4 this function is called four times, only the current call is skipped if the button is pressed. The following calls are not skipped, because your reset buttonPressed back to false.
There is no need for this, as it's already reset back to false at the beginning of setBrightness.


text:
Reading data by port manipulation (Arduino Due)
I have shorted the 23rd pin of port A with 3.3v output pin (i.e. tieing 23rd pin of port A to logic high). Now I am trying to read the 23rd pin of port A by using following code-
void setup() {
  Serial.begin(9600); // put your setup code here, to run once:
  char print_str[40];
  REG_PIOA_PER = 0x00800000;   //Write 1's to A register pins to override other peripherals and allow GPIO use for pins
  REG_PIOA_ODR = 0x00800000;   //Set A register pins to INPUT
  sprintf(print_str, "\n%08X", REG_PIOA_PDSR);
  Serial.println(print_str);
}

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

According to the code, the serial output should be 0x00800000. But I am always getting 0. Could you please tell me, what is going wrong?

23rd pin is PA22 ... did you connect the correct pin?

Check the value of REG_PIOA_WPMR.

Hint: Take a look at the GPIO library for SAM. There is an initialization missing. https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/SAM/GPIO.h

source: Stack Exchange

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

sort: votes


text:
Low voltage security
I'm building a circuit with a GPS sensor and an esp32. My input voltage is designed to be 5V but I experienced some issues where people put lower charger in input (<4V). As a result my esp32 will boot but will functions erratically.
As I'm quite new with components and circuits, I was wondering if there was a way to ensure no current will go to my esp32 unless the input voltage is at least 5V?
Board being used: Espressif esp32 devkitc 4
https://docs.espressif.com/projects/esp-idf/en/latest/get-started/get-started-devkitc.html
Thanks for your help

What you are looking for is a power-on-reset generator. A workaround in software could be to wait some ms before initializing any peripheral device. How do you know your esp boots and in which way does it behave erratically? Usually the esp's brownout detector triggers a reboot when the voltage drops too far

As far as I can see, you can set the brownout detection to a higher value. Default is CONFIG_BROWNOUT_DET_LVL_SEL_0 which is 2.4V. You can change it upto CONFIG_BROWNOUT_DET_LVL_SEL_7 which is 2,74V. But I think the issue might be with the voltage regulator that converts the 5V down to 3.3V.

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


text:
PUT request: PHP code to Arduino HTTPClient
I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code.
I'm thinking that I'm missing something in adding header.
Here is my PHP code :
       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );

and here is the corresponding Arduino IDE code:
    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }

The error I'm getting is :

The MAC signature found in the HTTP request
  'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any
  computed   signature.....

Although the HMAC signature created from same String works in PHP
here is the reference page of the API:
https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
Thanks

the http.PUT(d); adds the Content-length header, Host header, User-Agent header, Accept-Encoding header and Connection header. Is it OK for the SharedKey authorization?

It looks like that error message is coming from the web-service; seems like this might be more debugging the webservice, than arudino. What status code are you getting?

the first code uses 'SharedKey mikeiot,' the second code uses 'SharedKey account_name:' could this be the problem? You are also hard coding the content-length in the second code, could you be sending an incorrect amount?

@Juraj I need custom header like given in Arduino code 'addHeader'. It's ok to send these headers. should I skip Content-length header?

@esoterik I'm getting 403 response code from the server and the error message shown in post

@esoterik the acount_name is same in the code just change in the post description. Now I have edited it

I got clue from @esoterik answer and manage to send request successfully.
The problem were in adding header parameter:
 http.addHeader("Content-Length",  "20");

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works.
Thanks for every one response


text:
Controlling Arduino from Raspberry Pi
I am trying to control an Arduino Leonardo R3 to run some code when "triggered" from a Raspberry Pi. This would be in a loop so that it can be run multiple times. I have set up the Raspberry Pi and tested it with an LED and the output is working fine.
I then connected this to the Arduino and checked for a HIGH input from the RPi using an if statement.
void setup() {
  pinMode(7,INPUT);
  if(digitalRead(7)==HIGH) {
    // CODE IN HERE
  }
}

I found that this did not work as the if statement was always true because of pullup resistors not being used. I would greatly appreciate some guidance on this.

setup() runs only once, when the board is switched on (or reset). You should test pin 7 in loop() instead.

How do you connect the Arduino with RPi?

The reason I put it in setup first was because if I did something wrong didnt want it to continue constantly.
I connected the GPIO from the RPi direct to the Arduino pin 7.

Be careful connecting the Raspberry Pi to the arduino directly. The 5V signals on the Arduino can damage the Raspberry Pi.

The Arduino is being used as an input, will this be OK?

I don't know for sure. But a bug in your arduino code that sets the the input pin as an output would be a problem.

Should you change setup (Arduino + RPi), consider an Arduino Yun: it's a Leonardo and a Linux box on one board

possible duplicate of Controlling Arduino from Raspberry Pi

What I am basically trying to do is, program Java on a PC to control the RPi GPIO which controls the Arduino to run some code. The reason I chose the RPi was because I had one and thought it would be a simple "read input" setup but if there is any other way of doing this then please let me know.

Just thought, what if the if statement was for a key event and Java ran this keydown event, would this work?

Voting to close this as unanswerable, since two years have passed without the necessary information ever being provided.  As pointed out in the very first comment, the posted code only runs once, hence it cannot determine what is "always" the state of the input as claimed.  Without any information about what aspect of the code's behavior is being observed and without any code that would generate observable output included in the question, this is unanswerable.

You have to verify, at least:
A. if the 3.3V of the RPi can be read as high on the Atmega, if so you can connect them without any resistor.
B. if not, you have to use a voltage adapter (yes, other components and many possible solutions), otherwise you RPi GPIO will be ruined if using a pullup on the 5V.
The pullup and pulldown, in this case, should be used when you are in A and the peripheral support the higher voltage. This is not the case.

No adapter or pullup is needed - an ATmega at 5v actually has a lower threshold for a "1" than the pi's 3.3v CPU does.

I have done this in a different manner.
I have used the UART TX pin of RPi connected to the RX pin of the arduino and sent serial messages from Arduino to RPi.
That worked fine.
But the thing is, what you have done is correct and has to work.
Please make sure that you have connected Arduino's ground and RPi ground together.

If you not do that and try the same code it has to work. Because the RPi and Arduino are in two different circuits, so in order to work, make them one make GROUND common.

I don't have much experience about Arduino boards connected to the Pi, never tried anything other than Arduino Due, but I do have some experiences with ATmega328P directly attached to the Pi. The ATmega is clocked at 12MHz instead of 16 to guarantee a stable state at 3.3V supply voltage.
Physical connection takes 5 signal wires besides the 3.3V power rail, with the ATmega talking with the Pi over SPI as a slave device, using both slave select lines, one at the SS pin and the other at RESET pin. This allows communication over proper hardware interfaces while eliminates the need of a programmer or preprogrammed chips as the ATmega use its SPI interface as ICSP, this setup essentially keep ICSP properly wired to the Pi at all times. An additional pin can be used as a IRQ pin from the ATmega to the Pi.
About the protocol that part is up to yourself. There are endless possibilities and you can implement anything that fits your need and easy to use.

That's possible, yes, but seems a lot more than what the poster is trying to achieve.  USB current limits on various pi models aside, one can also plug the Arduino into the pi's USB instead of a PC's.

I have built myself a Arduino-like shield for Pi based on this idea. And it uses fresh chips, no bootloader required.

That's nice, but a lot more work and not really what the poster seems to be trying to do at this point.

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


text:
Cheap 2-5mb memory to use with arduino
I'm looking for a storage solution for small files that would be moved into a small sensor running arduino-like processor.
Ideally the single memory unit would be cheap (in 1-10 cents range), but the memory can be very limited (several megabytes).
The closest I've got so far is small SD Memory card, but the smallest 4GB ones cost several dollars (at least bought in quantities < 100). Anything else I should be looking at?

1-10 cents for several megabytes? What is your volume going to be, tens of millions?

You can try to find some cheap SPI Flash chips out there. WinBound has one DIP8 of 8MB. The retailer price can be quite high ($2-$3) but I a, sure you can find much better prices in small quantities (http://www.findchips.com/).

You should clarify further what you are looking for, to do what and to use it from what system (voltage, I2C, SPI...)

When going for minimal cost it often works the other way around: see what you can get cheapest, then figure out how you can adapt your system to work with it.  But I'd probably do my proof-of-concept prototypes with SPI flash too (though in SMT packages).

@ChrisStratton That's exactly my question. I'm in a prototyping phase and the cost of memory is a biggest consideration that's why I'm looking aroudn for the options. I'm ready to create solution around it.

@IgnacioVazquez-Abrams Considering you can easilly get a 2GB micro SD card for ~ 2$  making a cost of mb at around 0.1 of a cent. I thought 10cents for 10mb doesn't seem that unreasonable. Feel free to correct me on that.

MicroSD cards are usually made in the tens of millions. But you wouldn't want to interface directly with the flash chip on it though.

So all you need is a micro SD of a few GB, a jeweler's saw, and a very steady hand.  By which I mean the cost is not a linear function of capacity

The reason that cost and capacity are not linear functions is that the cost of the package is a substantial part of the overall cost. You want to find a component that has the amount of memory that you need and that is produced in quantity.

Do the files need to be persistent across reboots – in other words, does it need to be non-volatile memory?

I assume that, if this is a cost sensitive item, you need a reliable supply of multiples (so looking for small SD cards on e-bay isn't a viable solution).
Does it need to be non-volatile storage? If it does't you may be able to find small 8-bit wide RAM chips at a pretty good price. If it needs to be non-volatile, you might look at individual flash chips. I found this one, an 8-bit by 512 KB Serial-SPI flash chip for £0.19 (about $0.28 US) in single units and £0.176 if you can by 100 at a time. I would expect DRAM chips and chips with a simpler interface to be less expensive (but you might end up spending more on interfacing the chips so it might end up as a wash).
If you're able to consider a variety of processor chips it might be worth looking for something that has adequate storage on chip. That might be the most cost effective way to get the space.

On ebay you can buy 2nd hand Nokia SD cards from old mobile phones which are 128MB or so and very cheap.

Even though interfacing with a SD card would ramp up the cost a ton...

How so?  Reliability is a pain, but most SD cards will talk something interoperable with SPI with moderately more software complexity than an SPI flash.

@ChrisStratton SD card readers cost at least $2-3, so it'd be just as easy to use a EEPROM chip. I don't know if the OP wants to be able to have a ton of "disposable" SD cards to use with one device or if he's just trying to minimize the overall cost...

@AnnonomusPenguin - No.  An SD card reader is useless with an Arduino (you talk SPI directly to the card), so the cost of one doesn't factor into to.  Sockets are cheap, and optional anyway, as if you don't intend to move the card to anything else you can just solder directly to it.

Good idea, but won't work in my case.

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


text:
RTC and SD work separately but not together
I am running a small project. I want to use an Arduino Mega 2560 v3, a PIR sensor, a micro SD card module, an RTC 1307 module, some LEDs, buttons and a buzzer. To enable and disable motion detection and when detection is found the time is saved to the SD card.
I wired everything together, coded and started to test. During tests, Arduino on bootup was restarting over and over. First, I was thinking that the problem is in the breadboard and connection. I checked it a few times and I didn't notice anything wrong. So I checked the code over and over. Still nothing.
So I started to test modules. And I found a problem. When I don't use in the sketch either the RTC or the SD card (physically they are still connected, because I am lazy) everything works fine. Arduino doesn't restart. I didn't use the SD module to write data, instead I used the serial port to show data. Everything works fine: I can see at what time is motion detected and Arduino prints it on the terminal.
In the second scenario, I didn’t use the RTC, only the SD module. This time again everything works fine. On the SD card I could read how many times motion was detected. This is weird because when I mix all together it doesn't work.
Here is my code:
// *********************************************
// INCLUDE
// *********************************************
#include <Wire.h>
#include <SD.h>
#include <SPI.h>
#include "RTClib.h"
// *********************************************
// DEFINE
// *********************************************
#define GREENLED 39
#define BTNON 11
#define REDLED 41
#define BTNOFF 9
#define BUZZ 3
#define PIR_PIN 10
//SD (na mega)
#define SD_CLK_SD 52
#define SD_MI 50
#define SD_MO 51
#define SD_CS 4

//RTC
#define RTC_SDA 20
#define RTC_SCL 21
#define RTC_DS 2

// *********************************************
// VARIABLES
// *********************************************
RTC_DS1307 rtc;
File myFile;
char godz[8];
char data[5];

int btnON;
int btnOFF;
int pirD;
bool stan_alarmu;

void wlAlarmu() {
  digitalWrite(REDLED,LOW);
  digitalWrite(GREENLED, HIGH);
  stan_alarmu=true;
  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("### Wlaczenie alarmu ### ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
}

void wylAlarmu(){
  digitalWrite(GREENLED, LOW);
  digitalWrite(REDLED,HIGH);
  stan_alarmu=false;
  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("### Wylaczenie alarmu ### ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
}

void alarm(){
  digitalWrite(GREENLED,LOW);
  digitalWrite(REDLED,HIGH);
  digitalWrite(BUZZ,HIGH);
  delay(500);
  digitalWrite(BUZZ,LOW);

  gettime();
  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("Alarm: ");
    myFile.print(" ");
    myFile.print(godz);
    myFile.print(data);
    myFile.println("");
    myFile.close();
  }
  delay(5000);
  digitalWrite(REDLED,LOW);
  digitalWrite(GREENLED,HIGH);
}

void blad() {
  while(1){
    digitalWrite(REDLED,HIGH);
    delay(500);
    digitalWrite(REDLED,LOW);
    delay(500);
  }
}

void gettime() {
  DateTime now = rtc.now();
  sprintf(godz,"%02d:%02d:%02d ",now.hour(),now.minute(),now.second());
  sprintf(data,"%d.%d",now.day(),now.month());
}

// *********************************************
// SETUP
// *********************************************
void setup() {
  //RTC
  Wire.begin();
  // Shield I2C pins connect to alt I2C bus on Arduino Due
  rtc.begin();
  if (!rtc.isrunning()) {
    blad();
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(BTNON,INPUT);
  pinMode(GREENLED, OUTPUT);
  pinMode(BTNOFF,INPUT);
  pinMode(REDLED, OUTPUT);
  pinMode(PIR_PIN,INPUT);
  pinMode(BUZZ,OUTPUT);

  //test seq
  digitalWrite(GREENLED,HIGH);
  digitalWrite(REDLED,HIGH);
  digitalWrite(BUZZ,HIGH);
  delay(100);
  digitalWrite(BUZZ,LOW);
  digitalWrite(GREENLED,LOW);
  digitalWrite(REDLED,LOW);
  delay(500);
  pinMode(SD_CS, OUTPUT);
  if (!SD.begin(SD_CS)) {
    blad();
  }
  digitalWrite(GREENLED,HIGH);
  delay(1000);
  digitalWrite(GREENLED,LOW);
  gettime();
  Serial.begin(9600);

  myFile = SD.open("dane.txt", FILE_WRITE);
  if (myFile) {
    myFile.print("####START SYSTEMU: ");
    myFile.print(godz);
    myFile.print(data);
    myFile.print(" ####");
    myFile.println("");
    myFile.close();
  }
  wylAlarmu();
}

void loop() {
  btnON = digitalRead(BTNON);
  btnOFF = digitalRead(BTNOFF);
  pirD = digitalRead(PIR_PIN);

  if(btnON == HIGH) {
    wlAlarmu();
    delay(2000);
  }
  if(btnOFF == HIGH) {
    wylAlarmu();
    delay(2000);
  }

  if(pirD==HIGH && stan_alarmu==true) {
    alarm();
  }
  delay(1000);
}

Please give an exact specification of the shields you are using. Perhaps there are some clues hidden.

My RTC module looks almost like this: http://www.arduino-projekte.de/index.php?n=45 datasheet is on bottom of page under  DS1307 Datenblatt PDF (ENG). SD microSD reader is made by Catalex  http://catalex.taobao.com/ but I couldn't find documentation on their site :)

It looks, as if you use the RTC-library from adafruit. Same for the SD library? My suggestion is, that the configurations of I²C-Bus for both modules are conflicting. Most probably concerning bitrate. You should have a look inside both libraries and check, which parameters they apply to the Wire-Library.

I coundn't find anything in libs. I found also that someone use rtc an sd library same as me and it works. http://www.michellechandra.com/physical-computing/activity-tracker-log-date-and-time-to-microsd-using-real-time-clock-and-arduino/

I tried to use 3 diffrent libs. Still nothing thats amazing.

Hmm, if you own a scope, you should check the stability of all voltages in your system. repeated rebooting hints to brownouts.

I don't have scope. Only multimeter. Voltage is between 4,86 - 4,90.

Have you tried using the hardware pin for SPI SS (it's 53, I assumed you're using an Arduino Mega by looking at your preprocessor directives). Sometimes weird things happen when you reassign this pin.

After long time i build new circut and new sketch. I used only rtc and sd, this time everything was working fine. There is no problem now. Something used to be wrong in past.

A common issue when using strings (character vectors) is that the vector size is not updated when the format is update. Check the size required for this data. Does it fit for the sprintf() statements?
char godz[8];
char data[5];

void gettime()
{
  DateTime now = rtc.now();
  sprintf(godz,"%02d:%02d:%02d ",now.hour(),now.minute(),now.second());
  sprintf(data,"%d.%d",now.day(),now.month());
}

What is the worst case size required?
Cheers!

I ran into the same problem lately. I have a work-around but don't have a clear explanation of this problem. As you initialize the different modules in your setup(), make sure to perform the SD card initialization first, then followed by the RTC's. Doing this completely sorted me out. However, I am yet to explain these results.
Though it is late, just in case anyone else runs into the same problem.

It is too late to answer but I had the same issue and spent a week to solve it. This will not be the exact solution. It worked and I think this is the easiest way to solve it.
First let me tell you my components:

WeMos D1 R2 (ESP8266)
MicroSD Card Adapter
DS3231 RTC (I tried with DS1302 but it did not work).

How I solved is, on setup part, first I initialized the RTC DS3231 then I set the built in Arduino clock to DS3231 RTC values. After that I initialized SD card. In this case you are not able to get RTC data in loop but you have it in built in Arduino clock and SD card works. If your Arduino lose electricity, then it will get the RTC data in setup again.
This solution solves it in someway.
Also there is no tutorial for how to connect these cards to WeMos D1 R2 so I want to share my connections.
SD Card    WeMos D1 R2
-------    -----------
SC      -> D14/SDA/D5
SCK     -> D13/SCK
MOSI    -> D11/MOSI
MISO    -> D12/MISO
VCC     -> 5V
GND     -> GND

RTC DS3231   WeMos
----------   -----
SCL        -> SCL/D15
SDA        -> SDA/D14
VCC        -> 3.3V
GND        -> GND

Also my code:
#include <Wire.h>
#include "RTClib.h"
#include <SD.h> //Load SD library
#include <SPI.h>
#include <time.h>
#include <TimeLib.h>
File file;
int chipSelect = 5;
RTC_DS3231 rtc;
bool not1024prev;
unsigned long timepast;
unsigned long timecurr;
int cnt = 0;
int rpm;

char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

void setup()
{

#ifndef ESP8266
    while (!Serial)
        ; // for Leonardo/Micro/Zero
#endif

    Serial.begin(9600);

    delay(3000); // wait for console opening

    if (!rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1)
            ;
    }

    if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        //rtc.adjust(DateTime(2018, 3, 11, 16, 29, 30));
    }
    DateTime now = rtc.now();
    setTime(now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());

    if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
    }
}

void loop()
{
    String curtime = String(year()) + "." + String(month()) + "." + String(day()) + "-" + String(hour()) + ":" + String(minute()) + ":" + String(second());

    Serial.println(curtime);
}

Are you using breakout boards as pictured in your links? Or Arduino shields?
Many Uno shields are almost, but not quite, compatible with Mega boards. It is possible there there is one or more pins that are not compatible between them.
If you're using breakout boards, double check all of the connections to the Mega. Could something be dragging down your power supply? Or actually grounding the reset pin? It would probably be one of the programmable I/O pins since the failure only depended on whether you used the SD library and seems not affected by the mere presence of the board.

I use very similar breakout boards as in pictures. I don't use shields. I check connections many times.

When using Catalex Micro SD Card module, there is a problem with the MISO output. It is not disabled on the SPI bus because of a hardware failure. To correct the problem pin 13 on the IC must be liftet from ground connection and put together with pin 8, that have the CS signal. Now the Card Works fine with other SPI modules. Take care when soldering - it is very small pins.
Best regards OZ7LM Leif

You should start to debug your code stepwise. I.e. insert debug output commands (print via serial) at some crucial points to find the block of code which resets your device. Then narrow it down, until you know the very command which breaks your setup.
Maybe, there will be more than one point in your software, which is responsible for the failure. Nonetheless you will be wiser after that.
Then you will probably have to dive into the guts of the libraries.
If you have identified some command or procedure call responsible for the reboot, it may be still a hardware issue. Writing SD-cards consumes considerable amount of power. If you supply your device solely via USB, I recommend buying an additional PSU and see, if the behaviour changes.
The next thing is to check the reset-signal on all of your shields and daughter-boards for unwanted connections like solder-bridges or single wire threads snipped of elswhere. Another funny thing are stacking connectors not matching the mainboard and shorting something on it.


text:
Slaving multiple Arduinos via SPI
I am attempting to use SPI communication between a Master Arduino Mega 2560, and standalone Slave Arduino Unos (4, to be exact).
The intention is for the Unos to do some trivial work and produce one byte of data that the Master will take from it, whenever needed. They produce this byte very quickly, and the SPDR is updated with a holding variable (a byte) when the slave is interrupted. The Slaves do not take data from the Master.
The standalone platforms are working 100% (doing the work without problem), and using a single Slave to perform the work, create the byte of data, and have a Master take that data from it, is also working 100%.
The issue When all four slaves are connected (all being powered from the Master), all sharing the MISO, MOSI, and SCK lines, each with its own unique SS line, I am getting xFF for my data byte (garbage data) from the primary slave. I am using the default Mode 0, and the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)... All other SPI lines are wired directly.
The other three slaves are floating their MISO lines (third state), and the Master has all four SS lines as outputs, and all are pulled HIGH in the Master setup. The primary slave I am attempting to communicate with is SS connected to the main SS on the Master (pin 53 on a Mega). I pull the pin LOW, grab the byte from the Slave, and then pull the line HIGH... still garbage.. but only when all four slaves are 'hooked up', like I said, it works fine with one Master, one Slave.
Anyone have thoughts as to what I could be neglecting, missing, etc??

Here is the slave schematic. What you can't see is that VCC and AVCC are tied to the 5V line from the 10-pin header (the connection to the master).

The external power supply I am currently using is added in parallel to the 5V/Grnd you see in the schematic. The power supply has a max current draw at 5V of 10A, so I'm pretty confident that power is not my issue now, unless I have missed something.
I just realized that the imgur image is hard to see, here is a cut-away that should be clearer.

There's a good chance you're running into power regulation issues, too. The regulator on any Arduino has barely enough thermal capacity to power its own microcontroller chip, and burdening it with four other Arduinos is likely to be overloading the master's regulator.

I was wondering about that as well, but it was something I read when setting up initially. I HAVE re-tested without the capacitor connected.. no change.

I have also externally powered the primary slave, when testing, to check the possible power issue

At this point, I think we're going to need a detailed schematic of your setup, along with the code you're using for the SPI communications.

The master and slave code I am using, just for testing, is from the Gammon Forums, http://www.gammon.com.au/forum/?id=10892. The only addition is that the other 3 slaves are simply floating their MISO pins (dummy code). Also, the master is setting all SS high (as outputs, of course) in the setup.

*This should never have been migrated it's an EE question that belongs on the EE site, not here.

the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)

Get rid of that for a start.

The other three slaves are floating their MISO lines (third state)

That's your problem. They should all be outputs. From the datasheet:

When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high.

As you can see from that, you should configure all the MISO pins as outputs. However the SPI hardware will turn them into inputs if SS is high. Thus only one slave (the one you set MISO as an output) is capable of responding at present.
You should probably set them as outputs after turning on SPI slave mode. eg.
  // turn on SPI in slave mode
  SPCR |= bit (SPE);

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

And generally, when you wonder about an Arduino-related topic, you check it out at Nick's website. eg http://www.gammon.com.au/spi It has become my habit to type http://www.gammon.com.au/ + whatever subject I want to learn more about as a a first choice...


text:
Concatenation of non constant character array with a string
I have an Arduino Duemilanove.
I read this page on string concatenation. Yet, it didn't include my case.
I have a non constant character array, that later gets a value.
char clat[11];
dtostrf(gps.location.lat(), 11, 6, clat);

I want to output this:
Latitude: 20.653425

So basically I want a final string that contains: "Latitude:" + the value of the nonconstant array.
Is it possible?

char clat[10+11+1] = "Latitude: ";
dtostrf(gps.location.lat(), 11, 6, clat+10);

Since you've named the buffer 'clat' I'm assuming it will always be used for latitude, so we've pre-initialized its size and contents, and we know where to begin the latitude value.
By the way, don't forget to size string buffers one more byte than the length of the maximum length string you intend to put in it.
Update 6/23/14:
From your other question and your comment to this answer, I'll revise my suggestion to this. The ..printf() functions are particularly easy to use, saves you (mis)counting buffer positions, and don't add much lot more code than the Serial() object already includes:
char outbuf[40+1];      // wider than nec, easier than counting
char clat[15+1]; clong[15+1]; // workspaces

sprintf(outbuf, "Latitude/Longitude: %s %s",
    dtostrf(gps.location.lat(), 10, 6, temp),
    dtostrf(gps.location.lng(), 10, 6, temp) );

This works because dtostrf() returns the address of the buffer you gave it; sprintf then takes that string (two of them in this case) when building your final output string.
The printf() functions are often deprecated for embedded systems. They're large (but see my comment about that above); and they're non-reentrant, so don't do that! In these low-end systems we don't often multi-thread anyway - just be aware of that if you do. And even if you have to remove them later and go back to printing piece by piece, they can save you a lot of headaches during development.
Here's another way that avoids both printf and the 32 bytes of work buffers:
char outbuf[40+1];

 strcpy(outbuf, "Latitude/Longitude: ");
 dtostrf(gps.location.lat(), 12, 6, outbuf+strlen(outbuf));
 dtostrf(gps.location.lng(), 12, 6, outbuf+strlen(outbuf));

We can't initialize outbuf unless it is 1) static, and 2) not going to be used more than once, since its initial conditions won't be the same the second time around. I've increased the field-widths of dostrf() to be sure the outputs of the won't be run-together for large values.

totally worked! But i have an extra question. Imagine i have two values a latitude and longitude. So char clat[11],clon[11]; And dtostrf(gps.location.lat(), 10, 6, clat); dtostrf(gps.location.lon(), 10, 6, clat); And i want a final string that is "Latitude/Longitude: 30.111111 20.111111". How do i do that? I tried char final[20 + 30m + 1] = "Latitude/Longitude: "; dtostrf(gps.location.lat(), 10, 6, clat+10); dtostrf(gps.location.lng(), 10, 6, clng+32); and other permutations of the numbers but none of these work. I get "Latitude/L 30.000000" Message is cut and 2nd value doesnt appera at all!

For "Latitude/Longitude: 30.111111 20.111111" literally, you would need char cfinal[39+1] = "Latitude/Longitude: "; dtostrf(gps.location.lat(), 11, 6, cfinal+20); dtostrf(gps.location.lat(), 11, 6, cfinal+30);. I'd probably make the array a little longer and make the dtostrf() fields a little wider. Lat/longs could go to -180.0.... If you plan for it now, your maintenance at a later time will easier.

I just read your other question on this topic. See my edited answer above - should help you with both questions.

It's possible and very easy to do. You can convert a character array to a string object with the String(char_array_name_here) function.
To do this you can just do this:
String output = "Latitude: " + String(clat);  //Make sure to add a space so it's not "Latitude:20.653425"

You can do this with any string, just remove the String() part because you don't need to convert a string to a string!
One thing to note: you can just do this code if you're outputting it to the serial console:
Serial.println("Latitude: " + clat);

Summary of edits: found a function I was searching for yesterday but couldn't find. Much simpler

Other links:

http://arduino.cc/en/Reference/StringObject: main documentation for the string datatype
http://arduino.cc/en/Tutorial/StringAdditionOperator how to append data to a string


text:
Is there any way to run binary code from RAM?
I am looking for an inexpensive single board computer that I could program in assembly language, using limited facilities to load the object code from a PC and simple I/O peripherals.
Ideally I would like to be able to write in a reasonable time all the code on the machine myself. I don't want an OS in the way, as I want to have a program that writes in RAM some code and then branches to execute it.
Arduino would probably be my best choice, as far as system simplicity suitable for assembly programming goes, but it has a Harvard architecture and it won't allow me to execute from RAM.
Years ago I was using a Von Neumann architecture 8-bit CPU that could branch execution to any address, no matter whether it was mapped to ROM, RAM or whatever. This is what I would like to do now.
I probably could write and load in Flash memory an interpreter of op codes written in RAM, but it is a very complex and time-consuming solution, unless virtual machines of this kind exist already.
Any suggestions on other workarounds with Arduino or of other micro-controllers I might use?
Thanks!
Pierre

The PIC32 is a Princeton (Von Neumann) architecture chip.  It's a MIPS CPU so is well documented and standardized, though somewhat more complex than a lowly AVR.  The chipKIT boards may be more to your liking.

Although optimized as a Harvard Architecture, the ARM Cortex-M series can execute from RAM at a tolerable efficiency loss and would still be a lot faster than an AVR when doing so.   At least a half dozen chip companies make widely used offerings based on licensing this core, and while many people use vendor and/or semi-standard libraries, it is entirely possible to do it all yourself based on the data sheets.  I went with STM32 first as their discovery boards are very cheap, work on Linux/OSX with open source tools, and can program chips on custom boards, but have now used Kinetis as well.

The main question is Why? Why do you require ASM execution from RAM? And what kind of assembly do you want to use? Since every architecture has its own language... Do you do this for learning purposes? Or you have a specific target?

I beg to differ, why I wished to do this is irrelevant to the question I asked at the time as this is not a workaround to some other issue. Incidentally, I followed Majenko's advice and I currently have a Uno32 plus external interfaces running assembly (and calling C functions from assembly), writing its own modified asm code in RAM and executing it.

Forth is what you are looking for :)

@ChrisStratton putting code in RAM, instead of Flash, can actually result in faster code, at least in those processors, in which part of the internal RAM is in the code region. (address up to 0x1FFFFFFF) . Flash is typically slow, and, despite the "memory accelerator/buffer" (which is simply a small cache), you never get a true 1-cycle access. Therefore you'll have a lot of penalties, especially if the code has a lot of jumps (the buffer must be refilled) and it's executing from Flash instead of RAM. Different thing is the external RAM, which might be very slow (e.g. due to bus constraints).

@next-hack if you have RAM optimized for code access, yes.  But many basic micros that permit code access to RAM are only optimized for data access to it - while you can run them from RAM, it's slower than running them from flash as the instruction fetch and data access have to share the same memory bus, when ordinarily they would not.  But if you have one specifically designed for this, then sure, go ahead.  And that might explain why (if I recall correctly) in some of the Kinetis parts the RAM sizes grow symmetrically around 0x20000000, rather than linearly above it as in say STM32's.

In my opinion the interpreter idea is much more feasible. The notion of writing, in assembler, code that itself generates machine code, in RAM, and then executes it, is itself incredibly complex.
You haven't said why you want to do this, so this is somewhat of an X-Y problem.

I don't want an o.s. in the way ...

The normal Arduinos do not have an OS in the way - basically the code you write is what gets loaded onto the chip.

In a word, no.  The inability to execute modifiable memory is a rather unusual limitation in this day and age, where most other nominally Harvard architecture devices are modified to be able to avoid that limitation.  Writing a software interpreter is both going to be a lot more work, and a lot less efficient, than dealing with one of the many inexpensive, high performance, and easy to use chips that has the necessary internal connections to simply execute code from RAM.  The slightly less efficient pipeline operation in that mode is still far, far ahead of software interpretation.

I think you are underestimating the requirement to have "a program that writes in RAM some code and then branches to execute it". Now if the question said "load some code from disk and execute it" well yes, that would be trivial on the architectures that support loading code into RAM. But to have code that generates machine code? A compiler/assembler in other words? Maybe I misunderstood the question as meaning "generate code" rather than "load code". But the OP said " I would like to be able to write in a reasonable time all the code on the machine myself." Sounds like code generation to me.

No.  If you are going to do runtime code modification, it is by far easier to directly generate machine code than to generate high level code and also have to create a compiler or interpreter as in your recommendation.   It might be worth spending some time hand-writing instructions to get some perspective.  And no, "write all the code on the machine myself" does not refer to run time code generation to begin with, but rather merely to creating original work vs. relying on other authors for supporting components.

I think this answer could be improved with a link to a list of interpreters that already run on Arduino. Is there a more complete list than http://playground.arduino.cc/CommonTopics/InterpretedLanguages ?

Here is a simple forth style shell for the Arduino that executes code from any of the memory storages (SRAM, EEMEM, EEPROM). Not the fastest interpreter but shows how the instruction fetch (memory access) and instruction pointer (call/return addresses) can be abstracted. https://github.com/mikaelpatel/Arduino-Shell

I'm impressed, Mikael. I wrote a Forth interpreter for the Apple II years ago. I doubt I can even find the code these days. Good old Forth, still alive and kicking! :)

@NickGammon I recently wrote a more traditional forth virtual machine (fvm) for the Arduino. It allows embedding a byte instruction interpreter in an Arduino sketch as it is multi-tasking (allows yield of the fvm). https://github.com/mikaelpatel/Arduino-FVM. There is a token compiler (runs on the Arduino :) and a traditional forth interactive interpreter. Please see the example sketches.

@MikaelPatel - well that's impressive! I used token mapping in my Pascal compiler years ago, and tail call reduction as well, mainly to squeeze the code into the available space. :)

authors: сергей толмачов


text:
Is it possible to package a sketch with dependent libraries for cross-platform compatibility?
I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.
I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.
Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?

I would suggest switching to UECIDE instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).
UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.
That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.

I installed this earlier today, and so far I'm liking it! I'm glad you pointed it out. I'll play with it a few more days before deciding to switch.

A way to do so is to include all the library files (*.cpp, *.h) in your sketch folder and then include them in your code.
There are many solutions that you might find handy in this link: How to organize my Arduino projects' structure for easy source control?

Thanks! That was a good link with lots of useful info. So far I'm liking the idea to include all the library files into the sketch folder. That will also help me with the problem of different sketches requiring different versions of a library.


text:
Asymmetric encryption on a Teensy?
I want to monitor an input and then send the information in an encrypted way that can't be easily unlocked even if a malicious actor gets access to the device itself. I'm new to using the Teensy although I have done a few simple things with Arduino microcontrollers. I was hoping to find out if anyone has implemented RSA or other asymmetrical encryption on a Teensy or to figure out if it has enough processing power to make it feasible. I would also accept using other Arduinos (I have an MKR1000 as well), for this but I assume because the Teensy has much better performance it's more likely to be able to do computationally expensive encryption.
This won't need to decrypt anything, it will only be sending data encrypted using the public key of the receiving user.

Your question can not be fully answered, because we don't know how many bytes per second you intend to encrypt. You should already be aware that asym. encryption methods like RSA only exchange symetric keys with asymetric technology. The pyload is en-/decrypted synchronous. If the hacker get's access to your device, the security depends on whether you have secured the private key with a password, and how secure the password is. 100% security is impossible. The internet is full of infos on teensy encryption, e.g.: https://forum.pjrc.com/threads/24327-RSA-encryption

I'm not able to access that site due to my VPN and archive.is appears to have the same issue. Can you share the relevant information here? I don't expect a black and white yes/no answer, I would accept info on encryption methods and/or how many bytes per second RSA encryption a Teensy is likely to be capable of.

I have not given you an answer you can accept. I just mentioned, that you give us too few information to answer the question "Is the teensy fast enough" and I pointed you to an page where the usage of an RSA lib  is explained. Please do not excpect me to write a complete program or library you can use, I have neither the time nor the intention to do so in my rare spare time. If you can access SO pages, why can't you access ordinary internet pages?

The site you've linked has blocked my VPN or IP addresses from my country, it seems. I am sorry. I would also be very surprised if anyone went to the trouble to write a library as a response to this question. Maybe I was unclear in wording, I meant I would accept answers that explain how to determine the speed of the encryption on the Teensy.

I'm sorry too, if it looked like I tried to offend or attack you. That was not my intention. The best way to determine the speed  of an crypt method is to use some libs and check wheter it works and how many through put one can archieve. The speed and RAM consumption  heavily depends on the algorithm that is used. So asynchronous encryption is very time consuming, but as I mentioned, it is mainly used to encrypt synchrounous keys. And synchronous en-/decryption is much more performant. But without having to chance to download a lib, I fear you have no chance to try out something.

A Hint: Try the following keywords in a search engine: RSA, Teensy, Relic. Probably you have access to the Relic project on GIT hub .  https://github.com/relic-toolkit/relic . Here is an older page: https://code.google.com/archive/p/relic-toolkit/

I'm a bit confused about your use of the word asynchronous. I'm not very familiar with cryptography so I don't know anything about synchronous vs asynchronous encryption, this isn't terminology I've heard used for encryption before. Did you mean asymmetric or is synchronicity something I need to look into?

@PeterPaulKiefer thank you for linking the relic toolkit. I will investigate. I'm concerned about the disclaimer on it "RELIC is at most alpha-quality software. Implementations may not be correct or secure and may include patented algorithms. There are many configuration options which make the library horribly insecure." I guess I assumed there would be something PGP-like out there for Arduinos... maybe it doesn't exist?

I fear you can not write a really good encryption for your project, if you do not learn how encryption works. That's nothing one can teach you here. Check the internet for information on synchronous, asynchronous,  encryption, RSA, DSA, Diffie Hellmann, Public key, Private Key. Then you understand the issue with the relic toolkit better and can decide if it is useful.

Synchronous encryption means you have only one key both endpoint must know. This key is used to encrypt and to decrypt a payload. The synchrounous methods are very performant compared to the asynchronous methods. Asynchrounous means you have two keys a public and a private key. You send the public key to the communication partner which uses it to encrypt a payload and then sends the encrypted payload to you. Only the private key can be used to decrypt the payload, but the public key can not be used for decryption.

I think we need to back up here and look at the big picture.  You say you want a system that can't easily be unlocked even if an assailant has the hardware itself.  But then he'd have access to the raw sensor output directly, and wouldn't even need to worry about any encryption.  Is there something I'm missing here?

@Boggyman An attacker would naturally have raw sensor data from the point of getting control of the system onward. But I would like for the attacker to not be able to decrypt data that was sent prior to obtaining the hardware, even if the attacker had somehow recorded it.

Teensy4.1 has 55 digital IO (serial) pins at up to 200MHz. The USB port supports 480mbps, and ethernet is 10/100mbps. You're limited to 32 DMA channels, though (complicated but these are used to access onboard peripherals/memory). You don't have much contiguous ram, either.
Now, you haven't explained what you're doing with this data. This matters because even though the CPU is running at 600MHz, asymmetric encryption is slow. Are you trying to perform real-time encrypted communication? Are you just sending or receiving data as well?
Nothing stopping you from asymmetrically encrypting on a Teensy. You can find the source code for the OpenSSL functions RSA_public_encrypt and RSA_private_decrypt.
This question goes into calculating how many CPU cycles are needed to encrypt X bytes of data.
However, asymmetric encryption has problems: Like I said, it's slow - specifically RSA, and the size of the data you can encrypt depends on the size of your key and padding.
If you want to communicate in something resembling real-time, you want to use hybrid encryption. You should read about how TLS works; the short version is that an asymmetric handshake occurs where the two parties agree on a symmetric key. Once you decide what your data actually is, you can quantize it (eg. TLS 'chunks' are up to 16KB which are then sent as multiple TCP packets) then both parties use the symmetric key to send/receive - which can encrypt large data chunks without issue.


text:
Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?
Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.
The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).
Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?
Edit:
Both the ESP8266 and the ESP32 Updater class check for an "IMAGE_MAGIC" value in the upload header; but that is defined as "ESP_IMAGE_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.
Edit 2:
Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like <sketch_name>.<board_name>.bin, we just compare the board name as part of the uploaded filename: if (upload.filename.indexOf(MATCH) > 0) ..., where MATCH is the respective board name. As they are pin compatible, we use "d1_mini.bin" and "d1_mini32.bin".
Edit 3:
When the webserver tries to abort the upload with 403 Forbidden (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a server.client().stop(), but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.
This is not really a final solution, so I'ld appreciate any better idea.
Richard

You could just try what happens if you perform such an "illegal" update. My guess is that booting an image intended for the other MCU would fail and be marked as corrupted firmware image. If esp8266 and esp32 have different flash sizes I would expect the bootloader to recognize the faulty firmware images

At least I once OTAed a 4MB-ESP32 with an image intended for an 8MB-ESP32, which failed (the esp declined booting this image and remained on the fw-version that was installed previously)

The bords we use have the same amount of flash size (4MB), and the updater class of the ESPs seem to accept any file as long as the "magic byte" is 0xE9, but that is the same for ESP32 and ESP8266. Tested this with small text file named "fake.d1_mini.bin" wth 0xE9 as first byte - did report no error on update, but crashed on reboot.

I assume you are the one creating the OTA update.  If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.

Thank you for your answer. This was also my first idea, but finding a signature somewhere in the uploaded file is a lot of work, as you do not know where the linker puts the signature. I thought of a simpler method...

You can force the linker to place a signature at a specific location. Or you can "abuse" an unused interrupt vector.


text:
Powering a Sim800L Module
I am trying to use a DC power supply. I am thinking whether I can use this power supply to provide power for Sim800L module. After some research, I gathered that the Sim800L module requires a max current of 2A during GPRS transmission at 3.8-4.2 V (4.0 recommended). With the power supply I can easily configure the voltage at 4.0V. My question is: for this setup, do I need a DC-DC Buck Converter as in this one for regulation/step-down (not sure which)?

Li-Po batteries blow up very easily and require specific hardware to charge (check drone power supply issues).  please  be VERY CAREFUL charging Li-Po batteries (if you are following https://lastminuteengineers.com/sim800l-gsm-module-arduino-tutorial/#supplying-power-for-sim800l-module).  Li-Po ba

The lab power supply you linked is serious overkill for your needs. It shouldn't need a separate voltage regulator or buck converter, since I assume that it provdes a voltage and current regulated supply.
A regulated, fixed voltage 4V power supply that can provide 2A is what you want. That will probably cost < 1/10 of the amount of the lab supply you linked. The challenge is to find a 4V supply. (Most regulated power supplies are either 3.3V or 5V, since those are common voltages for solid state electronics.)
That said, the linear voltage regulators are usually adjustable with a decent voltage range using a resistor.
You could always build your own voltage regulator using a linear voltage regulator rated for 2A, plus a resistor and a couple of capacitors. You could either feed it from an unregulated 6V power supply or use a transformer, bridge rectifier, and capacitor to provide an unregulated DC input to a voltage regulator.
Edit:
With a little googling I found a few 4V 2A power supplies online. This one, for example:
https://www.alibaba.com/product-detail/US-AC110-220V-To-DC-4V_62155516966.html?spm=a2700.7724857.normalList.14.a5e64009aUU1ln&s=p
(That link is to a wholesale manufacturer that sells them in volume, but you may be able to find the same supply for single unit sale. A 2A switching 4V supply would meet your needs as well)


text:
Breadboard arduino uno not working properly
Is there any mistake in the circuit of arduino uno on breadboard... I am using arduino uno board to program this 328p mcu and after that i remove 328p from arduino uno board and placing on breadboard as shown in circuit diagram. But mcu is not working(i.e the motors are not and other devices connected to mcu are not working) But when i connect reset,vcc,gnd pins of 328p on breadboard to arduino uno board without 328p on it then its working fine and all devices are working according to my program.. even when  i connect those reset,vcc and gnd pins to reset,vcc,gnd of  any usb asp programmer then also its working fine(*even programmer is not plugged in to pc). Its very strange behavior even if i disconnect any of these reset,vcc,gnd cables then also its not working... Is there any errors in circuit...please help me out

That schematic is very hard to follow. You should use GND and VCC symbols instead of nets for your power and ground.

@Majenko i have added another circuit of eliminating  devices connected to it.. can you have a look at it..

Does it have to have all three connections to the Uno? Have you tried all different combinations of connections to see which work and which don't?

yes reset,vcc,gnd pins of 328p on breadboard has to connect same pins of any programmer usbasp or uno board with empty 328p..

Try measuring the voltage at the reset pin. It sounds like something on your board is pulling the reset line low. Also you schematic uses a weird symbol for the reset pins pull-up resistor.

Again i have verified the reset circuit... i found that after powering on the code is not running.. i have manualy reset 328p by sorting reset pin to ground .. then the code works fines... whats the problem in my circuit? i have to manually reset every time to get it working.. is the any thing to implement in my circuit that it can automatically reset at power on..

Problem solved by adding 100nf capacitor between reset and ground.... Which enables a auto reset function after every time powering on..
from this arduino forum i got this solution
Thank you everyone


text:
Modular Coding - What types of code portions to convert into library files? Rationale and methods?
I'm working on documentation and combining 2 pieces of code for testing parts of a larger project.
I'm supposed to comment and make the code very clear to people who will use it later and make sure it's modular. I'm supposed to make header files, to reference function chunks in the main code from just the #include(s).
I understand in C++, that the convention is that for each header files(?), .h, there is a .cpp, where the .h is the header file that declares all the content, and that the .cpp is where you define the .h, ie. implementation.
My supervisor told me to put more parts of the code into library files, because additional components will be added in the future -

but confused because all the length comes from using already existing
  library files, just a specific pattern of calling pre-defined
  functions.

If I put the files into a .h, how do I reference all the calls?
Make a void setup () {}?
The compiled code is 348 lines right now. All it has are some #include(s), code to calibrate and read from 2 different sensors using I2C and SPI protocols, with 1 shared master an Adafruit Bluefruit nRF52832, and comments with links to datasheets.
The bulkiness is in the set-ups and the different ways to  represent data (have 24 lines just to print out data from 1 sensor).
Should the entire code be just calling built in functions from a library file? So people who read the code don't see the details so much?

It's very subjective what should and shouldn't be put in a library.
I use the simple rules:

If it's an atomic piece of code like a hardware driver, it's a library.
If it's something that could be used in multiple sketches, it's a library.

Maybe things like configuration options could be put in a header file (not a library - a header file in the sketch folder).
You could maybe split portions of your sketch into C++ files or INO files within the sketch (not a library - files in the sketch folder, and using INO files is easier since you don't need header files, the IDE does it all for you) to group things logically together and make it easier to manage (all the LCD code in one file, all the temperature sensor code in another file, that kind of thing).

Thank you @Majenko. Will look into code examples more and try some stuff out.

When you say header file, you mean C++ .h and .cpp files. I have to define some of the functions in a .h and then do the implementation in the .cpp like normal C++. I don't know why, but when I heard header file, it sounded to me like just one file. https://www.youtube.com/watch?v=2pxYEwaMtaI

.h and .CPP files are not bound together in pairs. You can have one without the other. .h files are a convenient way of sharing chunks of code between .c and .CPP files. .CPP files get compiled.

C++ has no concept of "header file". That is all handled by the C Preprocessor (confusingly called CPP). When you #include a file it is literally included verbatim at that point. C++ doesn't know about it - it only sees the content.

Thanks - Majenko. Looked up more stuff on preprocessing and https://www.tutorialspoint.com/cprogramming/c_header_files.


text:
Creating an array, assigning a value to each indices, and assessing the array
I am trying to create an unassigned array of size 512 and then assigning a reading to each indices. I want to get the start time before and after the loop and only run it once. Then I want to know how to retrieve the readings and serialprint the values after the loop. So far this is what I have but I don't think it is running as I want it to. I was able to get the start time but I'm not sure if it is running afterwards. Any help is greatly appreciated. Thanks!
void setup() {
int Vs[512] = {};
int analogPin = A0; // turn pin A0 on
pinMode(9, INPUT);
Serial.begin(9600); // setup serial
analogWrite(9, pow(2, 7)); //LED power 0
int time = micros();
Serial.println(time);
}

void loop() {
int i;
for (int i = 0; i <= 511; i++); { //loop setup for 512
int c = analogRead(A0) * (5.000/1024.000);
int Vs[i] = {c};
Serial.println(Vs[i]);
}
int stoptime = micros();
Serial.println(stoptime);
}

void stop() {
while(1);
}

if you want to run the code only once, then put the code in the setup() block ... leave the loop() block empty

why do you have a stop() function? ... you never call it

make the array global. and it is too large for Uno. and Vs[i] = analogRead(A0) * (5.000/1024.000);

There are multiple issues with your program. The most obvious is that,
if you define a variable multiple times, you end up with mutliple
different variables that share the same name. For example:
void setup() {
    int Vs[512] = {};  // this Vs is local to setup()
}

void loop() {
    int i;  // this i is local to loop()
    for (int i = 0;  // this other i is visible within the for loop only
            i <= 511;
            i++)
        ;  // this is the body of the for loop
    {
        ...
        int Vs[i] = {c};  // this Vs is local to loop()
    }
}

Another issue I pointed out in the snippet above is that a semicolon by
itself is an empty (i.e. do-nothing) statement. Thus you for loop is
empty.
There is no point in defining a constant such as analogPin = A0 if you
don't use it.
The value returned by micros() is not an int, it's an
unsigned log.
If you store a voltage in volts in an int, you get a very poor
resolution of one volt. You could store in a float, but that would
fill up the memory of your Arduino. I would rather store the raw
readings, and convert to volts only for printing.
Serial.println() takes time, and you are doing this during the timed
part of your code, which is probably unintended.
Here is a version of your program that may better reflect your
intentions. It takes 512 analog readings, stores them in an array, then
prints them and reports the time taken to do the readings. Then it waits
for one second and repeats the whole thing again.
const uint8_t analogPin = A0;
const int readings_count = 512;
int Vs[readings_count];

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

void loop() {
    // Take a run of analog readings.
    unsigned long start_time = micros();
    for (int i = 0; i < readings_count; i++) {
        Vs[i] = analogRead(analogPin);
    }
    unsigned long stop_time = micros();

    // Print the readings.
    Serial.println("Voltage readings:");
    for (int i = 0; i < readings_count; i++) {
        Serial.println(5.0/1024 * Vs[i]);
    }
    Serial.print("Data recorded in ");
    Serial.print(stop_time - start_time);
    Serial.println(" µs");
    Serial.println();

    // Wait before the next run.
    delay(1000);
}

If you really want to run only one iteration of the process, then you
can just replace delay(1000); by exit(0);. Alternatively, move the
body of loop() to the end of setup(), and keep an empty loop().


text:
Why is this code not working?
So I am trying to use Port Manipulation to turn on LEDS but I need to use PORT Manipulations for specific reasons.
//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
PORTA =  B0000000; //29--->22
PORTC =  B0000000; //37--->30
PORTD =  B0000000; //45--->38
}

void loop(){
 PORTA =  B1000100;
 PORTC =  B0101000;
 PORTD =  B0000010;
 delay(1000);

 PORTA =  B1010000;
 PORTC =  B0001010;
 PORTD =  B0100000;
 delay(1000);

 PORTA =  B0010100;
 PORTC =  B0100010;
 PORTD =  B0001000;
 delay(1000);

}```
Heres the code for Arduino Mega 2560

You need to set the ports to output first, before you can use them.
To do that you use the DDRx (Data Direction) registers.  Your code should look like:
//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
    // Set the pins all to output
    DDRA = 0xFF;
    DDRC = 0xFF;
    DDRD = 0xFF;

    PORTA =  B0000000; //29--->22
    PORTC =  B0000000; //37--->30
    PORTD =  B0000000; //45--->38
}

void loop(){
    PORTA =  B1000100;
    PORTC =  B0101000;
    PORTD =  B0000010;
    delay(1000);

    PORTA =  B1010000;
    PORTC =  B0001010;
    PORTD =  B0100000;
    delay(1000);

    PORTA =  B0010100;
    PORTC =  B0100010;
    PORTD =  B0001000;
    delay(1000);
}

You can read more about direct port manipulation here.