Hello everyone,
I'm trying to optimize my cod as much as possible.
The main problem is at the end, I don't know how to declare digitalWrite(act_pneu,piston_state); in port register. Thank you!
#define sensor_laser_1 2 // pin 2 pentru senzor laser intrare
#define sensor_laser_2 3 // pin 2 pentru senzor laser iesire
#define S0 4 // frecventa scalare
#define S1 5 //frecventa scalare
#define S2 6 // HIGH pentru verde
#define S3 7 // HIGH pentru verde
#define sensorOut1 8 // citire culoare pe pinul 8
#define act_pneu 11 // pin 11 pentru actionare piston
int piston_state = LOW; // definire piston stare initiala
unsigned long starTime = 0; // start arduino
const long interval = 2000;
bool flag = false; // setare interval asteptare dupa 2 sec
int laser1 = digitalRead(sensor_laser_1); // citire senzor laser intrare
int laser2 = digitalRead(sensor_laser_2); // citiare senzor laser iesire
int culoare1 = 0;
void setup()
{
//Serial.begin(9600);
pinMode(sensor_laser_1, INPUT);//define detect input pin
pinMode(sensor_laser_2, INPUT);//define detect input pin
pinMode(sensorOut1, INPUT);
pinMode(act_pneu, OUTPUT); //define ACTION output pin
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
digitalWrite(S0,HIGH);
digitalWrite(S1,LOW);
digitalWrite(S2,HIGH);
digitalWrite(S3,HIGH);
}
void loop()
{
// Senzor culoare
culoare1 = pulseIn(sensorOut1, LOW);
if(culoare1 <100)
{
piston_state= HIGH; // cilindru pe ON
starTime = millis();
flag = true;
}
if (flag && millis() - starTime >= interval)
{
piston_state = LOW;
flag = false;
}
digitalWrite(act_pneu,piston_state);
}
To do this by direct port addressing is going to save you 4uS at the most. Is it worth it? You seem to be doing it every time round the loop which is wasteful. Try moving it to only execute it when piston_state changes, that will save you a lot more time.
To do this by direct port addressing then find the port and bit position of pin 11. Then read the current port value, apply a mask and store it back.
The mask should be a bit pattern that has a one in the bit position of pin 11 with zeros in all the other bits when you are setting bit 11 high. The mask is applied using an logic OR operation.
The mask should be a bit pattern that has a zero in the bit position of pin 11 with ones in all the other bits when you are setting bit 11 low. The mask is applied using an logic AND operation.
No it is all written in C so you can change it if you want. Perhaps it is better to take the original code, change it and change the name of the function so you have a choice of using it.
Anyway I think you can specify a timeout period in the call, check out the documentation.
Maybe 'pulseIn()' wasn't the right tool for the job. What is it that you are trying to do? What is producing the pulses? What does it mean when the pulse length is less than 100 microseconds? You have a bunch of input and output pins that you have not used yet so is this just a small part of a larger project?