servo and photoresistor in http routes
This commit is contained in:
parent
80bedd3cb3
commit
737a2e2fd3
15
src/controller/photoresistor.ts
Normal file
15
src/controller/photoresistor.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { Request, Response } from "express";
|
||||
import { board } from "../setup";
|
||||
import { analogRead } from "../promises";
|
||||
|
||||
export async function readResistor (req: Request, res: Response): Promise<Response<string, any>> {
|
||||
const { p } = req.params;
|
||||
const pin: string = req.params.p.startsWith("A") ? req.params.p.slice(0, p.length) : req.params.p;
|
||||
|
||||
const resistance = await analogRead(board, pin);
|
||||
|
||||
return res.status(200).json({
|
||||
status: 200,
|
||||
message: `Analog pin ${p} resistance as ${resistance}°`
|
||||
});
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
import { Request, Response } from "express";
|
||||
import { board } from "../setup";
|
||||
|
||||
export function rotateServo (req: Request, res: Response): Response<string, any> {
|
||||
const { p } = req.params;
|
||||
const pin: string = req.params.p.startsWith("A") ? req.params.p.slice(0, p.length) : req.params.p;
|
||||
const angle: number = Number.parseInt(req.params.ang);
|
||||
|
||||
if (Number.isNaN(angle)) {
|
||||
return res.status(400).json({
|
||||
status: 400,
|
||||
message: 'Invalid angle param, it should be integer'
|
||||
});
|
||||
}
|
||||
|
||||
board.servoWrite(pin, angle);
|
||||
|
||||
return res.status(200).json({
|
||||
status: 200,
|
||||
message: `Pin ${p} rotate as ${angle}°`
|
||||
});
|
||||
}
|
@ -11,7 +11,7 @@ export function digitalRead (board: Board, pin: number): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
export function analogRead (board: Board, pin: number): Promise<number> {
|
||||
export function analogRead (board: Board, pin: string): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
board.analogRead(pin, (val) => {
|
||||
resolve(val);
|
||||
|
@ -4,6 +4,9 @@ import { Router } from "express";
|
||||
import { readLed, readRgbLed, writeLed, writeRgbLed } from "../controller/led";
|
||||
import { readPin, setPin } from "../controller/pin";
|
||||
import { piezoNoTone, piezoPlayNotes, piezoTone } from "../controller/piezo";
|
||||
import { rotateServo } from "../controller/servo";
|
||||
import { readResistor } from "../controller/photoresistor";
|
||||
|
||||
import { isPinNumeric } from "../middleware/pin";
|
||||
|
||||
const router: Router = Router();
|
||||
@ -25,4 +28,9 @@ router.patch('/piezo/', piezoTone);
|
||||
router.patch('/piezo/stop/', piezoNoTone);
|
||||
router.patch('/piezo/music/', piezoPlayNotes);
|
||||
|
||||
// for real-time communication is deprecated and not recommended
|
||||
// use other protocol like websocket instead
|
||||
router.patch('/servo/:p/:m', rotateServo);
|
||||
router.get('/photoresistor/:p', readResistor);
|
||||
|
||||
export default router;
|
Loading…
x
Reference in New Issue
Block a user